home *** CD-ROM | disk | FTP | other *** search
/ kermit.columbia.edu / kermit.columbia.edu.tar / kermit.columbia.edu / tmp4 / ckucmd.c < prev    next >
C/C++ Source or Header  |  2009-10-16  |  223KB  |  7,910 lines

  1. #include "ckcsym.h"
  2.  
  3. char *cmdv = "Command package 9.0.167, 16 October 2008";
  4.  
  5. /*  C K U C M D  --  Interactive command package for Unix  */
  6.  
  7. /* (In reality, it's for all platforms, not just Unix) */
  8.  
  9. /*
  10.   Author: Frank da Cruz (fdc@columbia.edu),
  11.   Columbia University Academic Information Systems, New York City.
  12.  
  13.   Copyright (C) 1985, 2009,
  14.     Trustees of Columbia University in the City of New York.
  15.     All rights reserved.  See the C-Kermit COPYING.TXT file or the
  16.     copyright text in the ckcmai.c module for disclaimer and permissions.
  17. */
  18.  
  19. #define TOKPRECHECK
  20.  
  21. #define DOCHKVAR
  22.  
  23. /* Command-terminal-to-C-Kermit character mask */
  24.  
  25. #ifdef OS2                /* K95 */
  26. int cmdmsk = 255;            /* (always was 255) */
  27. #else                    /* All others... */
  28. int cmdmsk = 255;            /* 31 Dec 2000 (was 127) */
  29. #endif /* OS2 */
  30.  
  31. #ifdef BS_DIRSEP            /* Directory separator is backslash */
  32. #undef BS_DIRSEP
  33. #endif /* BS_DIRSEP */
  34.  
  35. #ifdef OS2
  36. #define BS_DIRSEP
  37. #endif /* BS_DIRSEP */
  38.  
  39. #define CKUCMD_C
  40.  
  41. #include "ckcdeb.h"                     /* Formats for debug(), etc. */
  42. #include "ckcker.h"            /* Needed for BIGBUFOK definition */
  43. #include "ckcnet.h"            /* Needed for server-side Telnet */
  44. #include "ckucmd.h"            /* Needed for everything */
  45. #include "ckuusr.h"                     /* Needed for prompt length */
  46.  
  47. #ifndef NOARROWKEYS
  48. #ifndef NOESCSEQ
  49. #ifdef VMSORUNIX
  50. #define USE_ARROWKEYS            /* Use arrow keys for command recall */
  51. #endif /* VMSORUNIX */
  52. #endif /* NOESCSEQ */
  53. #endif /* NOARROWKEYS */
  54.  
  55. #undef CKUCMD_C
  56.  
  57. _PROTOTYP( int unhex, (char) );
  58. _PROTOTYP( static VOID cmdclrscn, (void) );
  59.  
  60. #ifdef CKLEARN
  61. _PROTOTYP( VOID learncmd, (char *) );
  62. #endif /* CKLEARN */
  63.  
  64. static char *moname[] = {
  65.     "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  66.     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  67. };
  68.  
  69. struct keytab cmonths[] = {
  70.   { "april",     4, 0 },
  71.   { "august",    8, 0 },
  72.   { "december", 12, 0 },
  73.   { "february",  2, 0 },
  74.   { "january",   1, 0 },
  75.   { "july",      7, 0 },
  76.   { "june",      6, 0 },
  77.   { "march",     3, 0 },
  78.   { "may",       5, 0 },
  79.   { "november", 11, 0 },
  80.   { "october",  10, 0 },
  81.   { "september", 9, 0 }
  82. };
  83.  
  84. #ifndef NOICP     /* The rest only if interactive command parsing selected */
  85.  
  86. #ifndef NOSPL
  87. _PROTOTYP( int chkvar, (char *) );
  88. extern int askflag, echostars;
  89. #endif /* NOSPL */
  90.  
  91. #ifdef CKROOT
  92. extern int ckrooterr;
  93. #endif /* CKROOT */
  94.  
  95. #ifdef IKSD
  96. extern int inserver;
  97. #endif /* IKSD */
  98.  
  99. int cmfldflgs = 0;            /* Flags for cmfld() */
  100. int cmkwflgs = 0;            /* Flags from last keyword parse */
  101. static int nomsg = 0;
  102. static int blocklvl = 0;        /* Block nesting level */
  103. static int linebegin = 0;        /* Flag for at start of a line */
  104. static int quoting = 1;            /* Quoting is allowed */
  105. static int swarg = 0;            /* Parsing a switch argument */
  106. static int xcmfdb = 0;            /* Flag for parsing chained fdbs... */
  107. static int chsrc = 0;            /* Source of character, 1 = tty */
  108. static int newcmd = 0;            /* See addcmd() */
  109.  
  110. #ifdef BS_DIRSEP
  111. static int dirnamflg = 0;
  112. #endif /* BS_DIRSEP */
  113.  
  114. /*
  115. Modeled after the DECSYSTEM-20 command parser (the COMND JSYS), RIP. Features:
  116.  
  117.  . parses and verifies keywords, filenames, text strings, numbers, other data
  118.  . displays appropriate menu or help message when user types "?"
  119.  . does keyword and filename completion when user types ESC or TAB
  120.  . does partial keyword and filename completion
  121.  . accepts any unique abbreviation for a keyword
  122.  . allows keywords to have attributes, like "invisible" and "abbreviation"
  123.  . can supply defaults for fields omitted by user
  124.  . provides command retry and recall
  125.  . provides character, word, and line deletion (but only from the end)
  126.  . accepts input from keyboard, command files, macros, or redirected stdin
  127.  . allows for full or half duplex operation, character or line input
  128.  . allows \-escapes for special characters
  129.  . allows specification of a user exit to expand variables, etc.
  130.  . settable prompt, protected from deletion, dynamically re-evaluated each time
  131.  . allows chained parse functions.
  132.  
  133. Functions:
  134.  cmsetp - Set prompt (cmprom is prompt string)
  135.  cmsavp - Save current prompt
  136.  cmgetp = Get current prompt
  137.  prompt - Issue prompt
  138.  cmini  - Clear the command buffer (before parsing a new command)
  139.  cmres  - Reset command buffer pointers (before reparsing)
  140.  cmkey  - Parse a keyword or token (also cmkey2)
  141.  cmswi  - Parse a switch
  142.  cmnum  - Parse a number
  143.  cmifi  - Parse an input file name
  144.  cmofi  - Parse an output file name (also cmifip, cmifi2, ...)
  145.  cmdir  - Parse a directory name (also cmdirp)
  146.  cmfld  - Parse an arbitrary field
  147.  cmtxt  - Parse a text string
  148.  cmdate - Parse a date-time string
  149.  cmcfm  - Parse command confirmation (end of line)
  150.  cmfdb  - Parse any of a list of the foregoing (chained parse functions)
  151.  
  152. Return codes:
  153.  -9: like -2 except this module already printed the error message
  154.  -3: no input provided when required
  155.  -2: input was invalid (e.g. not a number when a number was required)
  156.  -1: reparse required (user deleted into a preceding field)
  157.   0 or greater: success
  158. See individual functions for greater detail.
  159.  
  160. Before using these routines, the caller should #include "ckucmd.h" and set the
  161. program's prompt by calling cmsetp().  If the file parsing functions cmifi,
  162. cmofi, or cmdir are to be used, this module must be linked with a ck?fio file
  163. system support module for the appropriate system, e.g. ckufio for Unix.  If
  164. the caller puts the terminal in character wakeup ("cbreak") mode with no echo,
  165. then these functions will provide line editing -- character, word, and line
  166. deletion, as well as keyword and filename completion upon ESC and help
  167. strings, keyword, or file menus upon '?'.  If the caller puts the terminal
  168. into character wakeup/noecho mode, care should be taken to restore it before
  169. exit from or interruption of the program.  If the character wakeup mode is not
  170. set, the system's own line editor may be used.
  171.  
  172. NOTE: Contrary to expectations, many #ifdef's have been added to this module.
  173. Any operation requiring an #ifdef (like clear screen, get character from
  174. keyboard, erase character from screen, etc) should eventually be turned into a
  175. call to a function that is defined in ck?tio.c, but then all the ck?tio.c
  176. modules would have to be changed...
  177. */
  178.  
  179. /* Includes */
  180.  
  181. #include "ckcker.h"
  182. #include "ckcasc.h"            /* ASCII character symbols */
  183. #include "ckucmd.h"                     /* Command parsing definitions */
  184.  
  185. #ifdef OSF13
  186. #ifdef CK_ANSIC
  187. #ifdef _NO_PROTO
  188. #undef _NO_PROTO
  189. #endif /* _NO_PROTO */
  190. #endif /* CK_ANSIC */
  191. #endif /* OSF13 */
  192.  
  193. #include <errno.h>            /* Error number symbols */
  194.  
  195. #ifdef OS2
  196. #ifndef NT
  197. #define INCL_NOPM
  198. #define INCL_VIO            /* Needed for ckocon.h */
  199. #include <os2.h>
  200. #undef COMMENT
  201. #else
  202. #define APIRET ULONG
  203. #include <windows.h>
  204. #endif /* NT */
  205. #include "ckocon.h"
  206. #include <io.h>
  207. #endif /* OS2 */
  208.  
  209. #ifdef OSK
  210. #define cc ccount            /* OS-9/68K compiler bug */
  211. #endif /* OSK */
  212.  
  213. #ifdef GEMDOS                /* Atari ST */
  214. #ifdef putchar
  215. #undef putchar
  216. #endif /* putchar */
  217. #define putchar(x) conoc(x)
  218. #endif /* GEMDOS */
  219.  
  220. #ifdef CK_AUTODL
  221. extern int cmdadl, justone;
  222. #endif /* CK_AUTODL */
  223.  
  224. extern int timelimit, nzxopts, nopush, nolocal, xcmdsrc, keepallchars;
  225.  
  226. #ifdef CKSYSLOG
  227. #ifdef UNIX
  228. #ifdef CKXPRINTF            /* Our printf macro conflicts with */
  229. #undef printf                /* use of "printf" in syslog.h */
  230. #endif /* CKXPRINTF */
  231. #ifdef RTAIX
  232. #include <sys/syslog.h>
  233. #else  /* RTAIX */
  234. #include <syslog.h>
  235. #endif /* RTAIX */
  236. #ifdef CKXPRINTF
  237. #define printf ckxprintf
  238. #endif /* CKXPRINTF */
  239. #endif /* UNIX */
  240. #endif /* CKSYSLOG */
  241.  
  242. /* Local variables */
  243.  
  244. static
  245. int psetf = 0,                          /* Flag that prompt has been set */
  246.     cc = 0,                             /* Character count */
  247.     dpx = 0,                            /* Duplex (0 = full) */
  248.     inword = 0;                /* In the middle of getting a word */
  249.  
  250. char *dfprom = "Command? ";             /* Default prompt */
  251. #ifndef NOLASTFILE
  252. char *lastfile = NULL;            /* Last filespec */
  253. static char *tmplastfile = NULL;    /* Last filespec candidate */
  254. #endif    /* NOLASTFILE */
  255.  
  256. int cmflgs;                             /* Command flags */
  257. int cmfsav;                /* A saved version of them */
  258.  
  259. static char pushc = NUL;
  260. static char brkchar = NUL;
  261.  
  262. #define CMDEFAULT 1023
  263. static char cmdefault[CMDEFAULT+1];
  264.  
  265. #ifdef DCMDBUF
  266. char *cmdbuf = NULL;            /* Command buffer */
  267. char *savbuf = NULL;            /* Buffer to save copy of command */
  268. char *atmbuf = NULL;            /* Atom buffer - for current field */
  269. char *atxbuf = NULL;            /* For expanding the atom buffer */
  270. static char *atybuf = NULL;        /* For copying atom buffer */
  271. static char *filbuf = NULL;        /* File name buffer */
  272. static char *cmprom = NULL;        /* Program's prompt */
  273. static char *cmprxx = NULL;        /* Program's prompt, unevaluated */
  274.  
  275. #ifdef CK_RECALL
  276. /*
  277.   Command recall is available only if we can make profligate use of malloc().
  278. */
  279. #define R_MAX 10            /* How many commands to save */
  280. int cm_recall = R_MAX;            /* Size of command recall buffer */
  281. int on_recall = 1;            /* Recall feature is ON */
  282. static int no_recall = 0;        /* Recall OFF for this cmd only */
  283. static int force_add = 0;        /* Force cmd into recall buffer */
  284. static int last_recall = -1;        /* Last recall-related action */
  285. /*
  286.   -1 = none
  287.    0 = CR (a command was entered)
  288.    1 = Up
  289.    2 = Down
  290. */
  291. int in_recall = 0;            /* Recall buffers are init'd */
  292. static int
  293.   current = -1,                /* Pointer to current command */
  294.   rlast = -1;                /* Index of last command in buffer */
  295. static char **recall = NULL;        /* Array of recall buffer pointers */
  296. #endif /* CK_RECALL */
  297. #else  /* !DCMDBUF */
  298. char cmdbuf[CMDBL+4];                   /* Command buffer */
  299. char savbuf[CMDBL+4];                   /* Buffer to save copy of command */
  300. char atmbuf[ATMBL+4];                   /* Atom buffer */
  301. char atxbuf[CMDBL+4];                   /* For expanding the atom buffer */
  302. static char atybuf[ATMBL+4];        /* For copying atom buffer */
  303. static char filbuf[ATMBL+4];        /* File name buffer */
  304. static char cmprom[PROMPTL+1];        /* Program's prompt */
  305. static char cmprxx[PROMPTL+1];        /* Program's prompt, unevaluated */
  306. #endif /* DCMDBUF */
  307.  
  308. /* Command buffer pointers */
  309.  
  310. #define PPVLEN VNAML            /* 20080305 Wolfram Sang (was 24) */
  311. char ppvnambuf[PPVLEN+1] = { NUL, NUL };
  312.  
  313. char * cmbptr = NULL;            /* Current position (for export) */
  314.  
  315. static char *bp,                        /* Current command buffer position */
  316.     *pp,                                /* Start of current field */
  317.     *np;                                /* Start of next field */
  318.  
  319. static int ungw,            /* For ungetting words */
  320.     atxn;                /* Expansion buffer (atxbuf) length */
  321.  
  322. #ifdef OS2
  323. extern int wideresult;
  324. #endif /* OS2 */
  325.  
  326. extern int cmd_cols, cmd_rows, local, quiet;
  327.  
  328. #ifdef TNCODE
  329. #ifdef IAC
  330. #undef IAC
  331. #endif /* IAC */
  332. #define IAC 255
  333. #endif /* TNCODE */
  334.  
  335. _PROTOTYP( static int gtword, (int) );
  336. _PROTOTYP( static int addbuf, (char *) );
  337. _PROTOTYP( static int setatm, (char *, int) );
  338. _PROTOTYP( static VOID cmdnewl, (char) );
  339. _PROTOTYP( static VOID cmdchardel, (void) );
  340. _PROTOTYP( static VOID cmdecho, (char, int) );
  341. _PROTOTYP( static int test, (int, int) );
  342. #ifdef GEMDOS
  343. _PROTOTYP( extern char *strchr, (char *, int) );
  344. #endif /* GEMDOS */
  345.  
  346. extern char * dftty;
  347.  
  348. /* The following are for use with chained FDB's */
  349.  
  350. static int crflag = 0;            /* Carriage return was typed */
  351. static int qmflag = 0;            /* Question mark was typed */
  352. static int esflag = 0;            /* Escape was typed */
  353.  
  354. /* Directory separator */
  355.  
  356. #ifdef GEMDOS
  357. static char dirsep = '\\';
  358. #else
  359. #ifdef datageneral
  360. static char dirsep = ':';
  361. #else
  362. #ifdef MAC
  363. static char dirsep = ':';
  364. #else
  365. #ifdef VMS
  366. static char dirsep = '.';
  367. #else
  368. #ifdef STRATUS
  369. static char dirsep = '>';
  370. #else
  371. static char dirsep = '/';        /* UNIX, OS/2, OS-9, Amiga, etc. */
  372. #endif /* STRATUS */
  373. #endif /* VMS */
  374. #endif /* MAC */
  375. #endif /* datageneral */
  376. #endif /* GEMDOS */
  377.  
  378. /*  H A S N O P A T H  */
  379.  
  380. /*  Returns 0 if filespec s includes any path segments; 1 if it doesn't. */
  381.  
  382. int
  383. hasnopath(s) char * s; {
  384.     char * p = NULL;
  385.     if (!s) return(0);
  386.     if (!*s) return(0);
  387.     zstrip(s,&p);
  388.     return(ckstrcmp(s,p,CKMAXPATH,filecase) == 0 ? 1 : 0);
  389. }
  390.  
  391. /*  C K S P R E A D  --  Print string double-spaced  */
  392.  
  393. static char * sprptr = NULL;
  394.  
  395. static char *
  396. ckspread(s) char * s; {
  397.     int n = 0;
  398.     char * p;
  399.     n = strlen(s);
  400.     if (sprptr)
  401.       free(sprptr);
  402.     sprptr = malloc(n + n + 3);
  403.     if (sprptr) {
  404.     p = sprptr;
  405.     while (*s) {
  406.         *p++ = *s++;
  407.         *p++ = SP;
  408.     }
  409.     *p = NUL;
  410.     }
  411.     return(sprptr ? sprptr : "");
  412. }
  413.  
  414. /*  T E S T  --  Bit test  */
  415.  
  416. static int
  417. test(x,m) int x, m; { /*  Returns 1 if any bits from m are on in x, else 0  */
  418.     return((x & m) ? 1 : 0);
  419. }
  420.  
  421. /*  K W D H E L P  --  Given a keyword table, print keywords in columns.  */
  422. /*
  423.   Call with:
  424.     s     - keyword table
  425.     n     - number of entries
  426.     pat   - pattern (left substring) that must match for each keyword
  427.     pre   - prefix to add to each keyword
  428.     post  - suffix to add to each keyword
  429.     off   - offset on first screenful, allowing room for introductory text
  430.     xhlp  - 1 to print any CM_INV keywords that are not also abbreviations.
  431.             2 to print CM_INV keywords if CM_HLP also set
  432.             4 if it's a switch table (to show ':' if CM_ARG)
  433.  
  434.   Arranges keywords in columns with width based on longest keyword.
  435.   Does "more?" prompting at end of screen.
  436.   Uses global cmd_rows and cmd_cols for screen size.
  437. */
  438. VOID
  439. kwdhelp(s,n,pat,pre,post,off,xhlp)
  440.     struct keytab s[]; int n, off, xhlp; char *pat, *pre, *post;
  441. /* kwdhelp */ {
  442.  
  443.     int width = 0;
  444.     int cc;
  445.     int cols, height, i, j, k, lc, n2 = 0;
  446.     char *b = NULL, *p, *q;
  447.     char *pa, *px;
  448.     char **s2 = NULL;
  449.     char *tmpbuf = NULL;
  450.  
  451.     cc = strlen(pat);
  452.  
  453.     if (!s) return;            /* Nothing to do */
  454.     if (n < 1) return;            /* Ditto */
  455.     if (off < 0) off = 0;        /* Offset for first page */
  456.     if (!pre) pre = "";            /* Handle null string pointers */
  457.     if (!post) post = "";
  458.     lc = off;                /* Screen-line counter */
  459.  
  460.     if (xhlp & 4)            /* For switches */
  461.       tmpbuf = (char *)malloc(TMPBUFSIZ+1);
  462.  
  463.     if ((s2 = (char **) malloc(n * sizeof(char *)))) {
  464.     for (i = 0; i < n; i++) {    /* Find longest keyword */
  465.         s2[i] = NULL;
  466.         if (ckstrcmp(s[i].kwd,pat,cc,0))
  467.           continue;
  468.  
  469.         if (s[i].flgs & CM_PSH    /* NOPUSH or nopush screening */
  470. #ifndef NOPUSH
  471.         && nopush
  472. #endif /* NOPUSH */
  473.         )
  474.           continue;
  475.         if (s[i].flgs & CM_LOC    /* NOLOCAL or nolocal screening */
  476. #ifndef NOLOCAL
  477.         && nolocal
  478. #endif /* NOLOCAL */
  479.         )
  480.           continue;
  481.  
  482.         if (s[i].flgs & CM_INV) {
  483. #ifdef COMMENT
  484. /* This code does not show invisible keywords at all except for "help ?" */
  485. /* and then only help topics (CM_HLP) in the top-level keyword list. */
  486.  
  487.         if ((xhlp & 2) == 0)
  488.           continue;
  489.         else if ((s[i].flgs & CM_HLP) == 0)
  490.           continue;
  491. #else
  492. /* This code shows invisible keywords that are not also abbreviations when */
  493. /* ? was typed AFTER the beginning of the field so the user can find out */
  494. /* what they are and (for example) why completion doesn't work at this point */
  495.  
  496.         if (s[i].flgs & CM_ABR)
  497.           continue;
  498.         else if ((xhlp & 3) == 0)
  499.           continue;
  500.         else if ((xhlp & 2) && ((s[i].flgs & CM_HLP) == 0))
  501.           continue;
  502. #endif /* COMMENT */
  503.         }
  504.         j = strlen(s[i].kwd);
  505.         if (!(xhlp & 4) || !tmpbuf) { /* Regular keyword table */
  506.         s2[n2++] = s[i].kwd;    /* Copy pointers to visible ones */
  507.         } else {            /* Switches */
  508.         ckmakmsg(tmpbuf,    /* Make a copy that shows ":" if */
  509.              TMPBUFSIZ,    /* the switch takes an argument. */
  510.              s[i].kwd,
  511.              (s[i].flgs & CM_ARG) ? ":" : "",
  512.              NULL,
  513.              NULL
  514.              );
  515.         makestr(&(s2[n2]),tmpbuf);
  516.         if (s[i].flgs & CM_ARG) j++;
  517.         n2++;
  518.         }
  519.         if (j > width)
  520.           width = j;
  521.     }
  522.     /* Column width */
  523.     n = n2;
  524.     }
  525.     if (s2 && (b = (char *) malloc(cmd_cols + 1))) { /* Make a line buffer   */
  526.     char * bx;
  527.     bx = b + cmd_cols;
  528.     width += (int)strlen(pre) + (int)strlen(post) + 2;
  529.     cols = cmd_cols / width;    /* How many columns? */
  530.     if (cols < 1) cols = 1;
  531.     height = n / cols;        /* How long is each column? */
  532.     if (n % cols) height++;        /* Add one for remainder, if any */
  533.  
  534.     for (i = 0; i < height; i++) {        /* Loop for each row */
  535.         for (j = 0; j < cmd_cols; j++)  /* First fill row with blanks */
  536.           b[j] = SP;
  537.         for (j = 0; j < cols; j++) {    /* Loop for each column in row */
  538.         k = i + (j * height);       /* Index of next keyword */
  539.         if (k < n) {            /* In range? */
  540.             pa = pre;
  541.             px = post;
  542.             p = s2[k];            /* Point to verb name */
  543.             q = b + (j * width) + 1; /* Where to copy it to */
  544.             while ((q < bx) && (*q++ = *pa++)) ; /* Copy prefix */
  545.             q--;                         /* Back up over NUL */
  546.             while ((q < bx) && (*q++ = *p++)) ;     /* Copy filename */
  547.             q--;                         /* Back up over NUL */
  548.             while ((q < bx) && (*q++ = *px++)) ; /* Copy suffix */
  549.             if (j < cols - 1) {
  550.             q--;
  551.             *q = SP;    /* Replace the space */
  552.             }
  553.         }
  554.         }
  555.         p = b + cmd_cols - 1;    /* Last char in line */
  556.         while (*p-- == SP) ;    /* Trim */
  557.         *(p+2) = NUL;
  558.         printf("%s\n",b);        /* Print the line */
  559.         if (++lc > (cmd_rows - 2)) { /* Screen full? */
  560.         if (!askmore())        /* Do more-prompting... */
  561.           goto xkwdhelp;
  562.         else
  563.           lc = 0;
  564.         }
  565.     }
  566.     /* printf("\n"); */        /* Blank line at end of report */
  567.     } else {                /* Malloc failure, no columns */
  568.     for (i = 0; i < n; i++) {
  569.         if (s[i].flgs & CM_INV)    /* Use original keyword table */
  570.           continue;            /* skipping invisible entries */
  571.         printf("%s%s%s\n",pre,s[i].kwd,post);
  572.         if (++lc > (cmd_rows - 2)) { /* Screen full? */
  573.         if (!askmore())        /* Do more-prompting... */
  574.           goto xkwdhelp;
  575.         else
  576.           lc = 0;
  577.         }
  578.     }
  579.     }
  580.   xkwdhelp:
  581.     if (xhlp & 4) {
  582.     if (tmpbuf) free((char *)tmpbuf);
  583.     for (i = 0; i < n; i++)
  584.       if (s2[i]) free(s2[i]);
  585.     }
  586.     if (s2) free(s2);            /* Free array copy */
  587.     if (b) free(b);            /* Free line buffer */
  588.     return;
  589. }
  590.  
  591. /*  X F I L H E L P  --  Given a file list, print names in columns.  */
  592. /*
  593.   Call with:
  594.     n     - number of entries
  595.     pre   - prefix to add to each filename
  596.     post  - suffix to add to each filename
  597.     off   - offset on first screenful, allowing room for introductory text
  598.     cmdirflg - 1 if only directory names should be listed, 0 to list all files
  599.     fs    - call fileselect() to decide whether to include each file.
  600.     The rest of the args are the same as for fileselect().
  601.  
  602.   Arranges filenames in columns with width based on longest filename.
  603.   Does "more?" prompting at end of screen.
  604.   Uses global cmd_rows and cmd_cols for screen size.
  605. */
  606.  
  607. int
  608. #ifdef CK_ANSIC
  609. xfilhelp(
  610.     int n, char *pre, char *post, int off, int cmdirflag,
  611.     int fs, char *sa, char *sb, char *sna, char *snb,
  612.     CK_OFF_T minsiz, CK_OFF_T maxsiz,
  613.     int nbu, int nxlist,
  614.     char ** xlist
  615. )
  616. #else
  617. xfilhelp(n,pre,post,off,cmdirflg,
  618.      fs,sa,sb,sna,snb,minsiz,maxsiz,nbu,nxlist,xlist)
  619.     int n, off; char *pre, *post; int cmdirflg;
  620.     int fs; char *sa,*sb,*sna,*snb; CK_OFF_T minsiz,maxsiz;
  621.     int nbu,nxlist; char ** xlist;
  622. #endif    /* CK_ANSIC */
  623.  {
  624.     char filbuf[CKMAXPATH + 1];        /* Temp buffer for one filename */
  625.     int width = 0;
  626.     int cols, height, i, j, k, lc, n2 = 0, rc = 0, itsadir = 0;
  627.     char *b = NULL, *p, *q;
  628.     char *pa, *px;
  629.     char **s2 = NULL;
  630. #ifdef VMS
  631.     char * cdp = zgtdir();
  632. #endif /* VMS */
  633.  
  634.     if (n < 1) return(0);
  635.     if (off < 0) off = 0;        /* Offset for first page */
  636.     if (!pre) pre = "";            /* Handle null string pointers */
  637.     if (!post) post = "";
  638.  
  639.     lc = off;                /* Screen-line counter */
  640.  
  641.     if ((s2 = (char **) malloc(n * sizeof(char *)))) {
  642.     for (i = 0; i < n; i++) {    /* Loop through filenames */
  643.         itsadir = 0;
  644.         s2[i] = NULL;        /* Initialize each pointer to NULL */
  645.         znext(filbuf);        /* Get next filename */
  646.         if (!filbuf[0])        /* Shouldn't happen */
  647.           break;
  648. #ifdef COMMENT
  649.         itsadir = isdir(filbuf);    /* Is it a directory? */
  650.         if (cmdirflg && !itsadir)    /* No, listing directories only? */
  651.           continue;            /* So skip this one. */
  652. #endif /* COMMENT */
  653.         if (fs) if (fileselect(filbuf,
  654.                sa,sb,sna,snb,
  655.                minsiz,maxsiz,nbu,nxlist,xlist) < 1) {
  656.                     continue;
  657.         }
  658. #ifdef VMS
  659.         ckstrncpy(filbuf,zrelname(filbuf,cdp),CKMAXPATH);
  660. #endif /* VMS */
  661.         j = strlen(filbuf);
  662. #ifndef VMS
  663.         if (itsadir && j < CKMAXPATH - 1 && j > 0) {
  664.         if (filbuf[j-1] != dirsep) {
  665.             filbuf[j++] = dirsep;
  666.             filbuf[j] = NUL;
  667.         }
  668.         }
  669. #endif /* VMS */
  670.         if (!(s2[n2] = malloc(j+1))) {
  671.         printf("?Memory allocation failure\n");
  672.         rc = -9;
  673.         goto xfilhelp;
  674.         }
  675.         if (j <= CKMAXPATH) {
  676.         strcpy(s2[n2],filbuf);
  677.         n2++;
  678.         } else {
  679.         printf("?Name too long - %s\n", filbuf);
  680.         rc = -9;
  681.         goto xfilhelp;
  682.         }
  683.         if (j > width)        /* Get width of widest one */
  684.           width = j;
  685.     }
  686.     n = n2;                /* How many we actually got */
  687.     }
  688.     sh_sort(s2,NULL,n,0,0,filecase);    /* Alphabetize the list */
  689.  
  690.     rc = 1;
  691.     if (s2 && (b = (char *) malloc(cmd_cols + 1))) { /* Make a line buffer */
  692.     char * bx;
  693.     bx = b + cmd_cols;
  694.     width += (int)strlen(pre) + (int)strlen(post) + 2;
  695.     cols = cmd_cols / width;    /* How many columns? */
  696.     if (cols < 1) cols = 1;
  697.     height = n / cols;        /* How long is each column? */
  698.     if (n % cols) height++;        /* Add one for remainder, if any */
  699.  
  700.     for (i = 0; i < height; i++) {        /* Loop for each row */
  701.         for (j = 0; j < cmd_cols; j++)  /* First fill row with blanks */
  702.           b[j] = SP;
  703.         for (j = 0; j < cols; j++) {    /* Loop for each column in row */
  704.         k = i + (j * height);       /* Index of next filename */
  705.         if (k < n) {            /* In range? */
  706.             pa = pre;
  707.             px = post;
  708.             p = s2[k];                       /* Point to filename */
  709.             q = b + (j * width) + 1;             /* and destination */
  710.             while ((q < bx) && (*q++ = *pa++)) ; /* Copy prefix */
  711.             q--;                         /* Back up over NUL */
  712.             while ((q < bx) && (*q++ = *p++)) ;     /* Copy filename */
  713.             q--;                         /* Back up over NUL */
  714.             while ((q < bx) && (*q++ = *px++)) ; /* Copy suffix */
  715.             if (j < cols - 1) {
  716.             q--;
  717.             *q = SP;    /* Replace the space */
  718.             }
  719.         }
  720.         }
  721.         p = b + cmd_cols - 1;    /* Last char in line */
  722.         while (*p-- == SP) ;    /* Trim */
  723.         *(p+2) = NUL;
  724.         printf("%s\n",b);        /* Print the line */
  725.         if (++lc > (cmd_rows - 2)) { /* Screen full? */
  726.         if (!askmore()) {    /* Do more-prompting... */
  727.             rc = 0;
  728.             goto xfilhelp;
  729.         } else
  730.           lc = 0;
  731.         }
  732.     }
  733.     printf("\n");            /* Blank line at end of report */
  734.     goto xfilhelp;
  735.     } else {                /* Malloc failure, no columns */
  736.     for (i = 0; i < n; i++) {
  737.         znext(filbuf);
  738.         if (!filbuf[0]) break;
  739.         printf("%s%s%s\n",pre,filbuf,post);
  740.         if (++lc > (cmd_rows - 2)) { /* Screen full? */
  741.         if (!askmore()) {     /* Do more-prompting... */
  742.             rc = 0;
  743.             goto xfilhelp;
  744.         } else lc = 0;
  745.         }
  746.     }
  747. xfilhelp:
  748.     if (b) free(b);
  749.     for (i = 0; i < n2; i++)
  750.       if (s2[i]) free(s2[i]);
  751.     if (s2) free((char *)s2);
  752.     return(rc);
  753.     }
  754. }
  755.  
  756. /*
  757.   Simpler front end for xfilhelp() with shorter arg list when no
  758.   file selection is needed.
  759. */
  760. int
  761. filhelp(n,pre,post,off,cmdirflg) int n, off; char *pre, *post; int cmdirflg; {
  762.     return(xfilhelp(n,pre,post,off,cmdirflg,
  763.             0,NULL,NULL,NULL,NULL,
  764.             (CK_OFF_T)0,(CK_OFF_T)0,0,0,(char **)NULL));
  765. }
  766.  
  767. /*  C M S E T U P  --  Set up command buffers  */
  768.  
  769. #ifdef DCMDBUF
  770. int
  771. cmsetup() {
  772.     if (!(cmdbuf = malloc(CMDBL + 4))) return(-1);
  773.     if (!(savbuf = malloc(CMDBL + 4))) return(-1);
  774.     savbuf[0] = '\0';
  775.     if (!(atmbuf = malloc(ATMBL + 4))) return(-1);
  776.     if (!(atxbuf = malloc(CMDBL + 4))) return(-1);
  777.     if (!(atybuf = malloc(ATMBL + 4))) return(-1);
  778.     if (!(filbuf = malloc(ATMBL + 4))) return(-1);
  779.     if (!(cmprom = malloc(PROMPTL + 4))) return(-1);
  780.     if (!(cmprxx = malloc(PROMPTL + 4))) return(-1);
  781. #ifdef CK_RECALL
  782.     cmrini(cm_recall);
  783. #endif /* CK_RECALL */
  784.     return(0);
  785. }
  786. #endif /* DCMDBUF */
  787.  
  788. /*  C M S E T P  --  Set the program prompt.  */
  789.  
  790. VOID
  791. cmsetp(s) char *s; {
  792.     if (!s) s = "";
  793.     ckstrncpy(cmprxx,s,PROMPTL);
  794.     psetf = 1;                          /* Flag that prompt has been set. */
  795. }
  796.  
  797. /*  C M S A V P  --  Save a copy of the current prompt.  */
  798.  
  799. VOID
  800. #ifdef CK_ANSIC
  801. cmsavp(char s[], int n)
  802. #else
  803. cmsavp(s,n) char s[]; int n;
  804. #endif /* CK_ANSIC */
  805. /* cmsavp */ {
  806.     if (psetf)                /* But not if no prompt is set. */
  807.       ckstrncpy(s,cmprxx,n);
  808. }
  809.  
  810. char *
  811. cmgetp() {
  812.     return(cmprxx);
  813. }
  814.  
  815. int
  816. cmgbrk() {
  817.     return(brkchar);
  818. }
  819.  
  820. int
  821. cmgkwflgs() {
  822.     return(cmkwflgs);
  823. }
  824.  
  825. /*  P R O M P T  --  Issue the program prompt.  */
  826.  
  827. VOID
  828. prompt(f) xx_strp f; {
  829.     char *sx, *sy; int n;
  830. #ifdef CK_SSL
  831.     extern int ssl_active_flag, tls_active_flag;
  832. #endif /* CK_SSL */
  833. #ifdef OS2
  834.     extern int display_demo;
  835.  
  836.     /* If there is a demo screen to be displayed, display it */
  837.     if (display_demo && xcmdsrc == 0) {
  838.         demoscrn(VCMD);
  839.         display_demo = 0;
  840.     }
  841. #endif /* OS2 */
  842.  
  843.     if (psetf == 0)            /* If no prompt set, set default. */
  844.       cmsetp(dfprom);
  845.  
  846.     sx = cmprxx;            /* Unevaluated copy */
  847.     if (f) {                /* If conversion function given */
  848.     sy = cmprom;            /* Evaluate it */
  849. #ifdef COMMENT
  850.     debug(F101,"prompt sx","",sx);
  851.     debug(F101,"prompt sy","",sy);
  852. #endif    /* COMMENT */
  853.     n = PROMPTL;
  854.     if ((*f)(sx,&sy,&n) < 0)    /* If evaluation failed */
  855.       sx = cmprxx;            /* revert to unevaluated copy */
  856.     else if (!*cmprom)        /* ditto if it came up empty */
  857.       sx = cmprxx;
  858.     else
  859.       sx = cmprom;
  860.     } else
  861.       ckstrncpy(cmprom,sx,PROMPTL);
  862.     cmprom[PROMPTL-1] = NUL;
  863.     if (!*sx)                /* Don't print if empty */
  864.       return;
  865.  
  866. #ifdef OSK
  867.     fputs(sx, stdout);
  868. #else
  869. #ifdef MAC
  870.     printf("%s", sx);
  871. #else
  872. #ifdef IKSD
  873.     if (inserver) {            /* Print the prompt. */
  874.         ttoc(CR);            /* If TELNET Server */
  875.         ttoc(NUL);            /* must folloW CR by NUL */
  876.         printf("%s",sx);
  877.     } else
  878. #endif /* IKSD */
  879.       printf("\r%s",sx);
  880. #ifdef CK_SSL
  881.     if (!(ssl_active_flag || tls_active_flag))
  882. #endif /* CK_SSL */
  883.       fflush(stdout);            /* Now! */
  884. #endif /* MAC */
  885. #endif /* OSK */
  886. }
  887.  
  888. #ifndef NOSPL
  889. VOID
  890. pushcmd(s) char * s; {            /* For use with IF command. */
  891.     if (!s) s = np;
  892.     ckstrncpy(savbuf,s,CMDBL);        /* Save the dependent clause,  */
  893.     cmres();                /* and clear the command buffer. */
  894.     debug(F110, "pushcmd savbuf", savbuf, 0);
  895. }
  896.  
  897. VOID
  898. pushqcmd(s) char * s; {            /* For use with ELSE command. */
  899.     char c, * p = savbuf;        /* Dest */
  900.     if (!s) s = np;            /* Source */
  901.     while (*s) {            /* Get first nonwhitespace char */
  902.     if (*s != SP)
  903.       break;
  904.     else
  905.       s++;
  906.     }
  907.     if (*s != '{') {            /* If it's not "{" */
  908.     pushcmd(s);            /* do regular pushcmd */
  909.     return;
  910.     }
  911.     while ((c = *s++)) {        /* Otherwise insert quotes */
  912.     if (c == CMDQ)
  913.       *p++ = CMDQ;
  914.     *p++ = c;
  915.     }
  916.     cmres();                /* and clear the command buffer. */
  917.     debug(F110, "pushqcmd savbuf", savbuf, 0);
  918. }
  919. #endif /* NOSPL */
  920.  
  921. #ifdef COMMENT
  922. /* no longer used... */
  923. VOID
  924. popcmd() {
  925.     ckstrncpy(cmdbuf,savbuf,CMDBL);    /* Put back the saved material */
  926.     *savbuf = '\0';            /* and clear the save buffer */
  927.     cmres();
  928. }
  929. #endif /* COMMENT */
  930.  
  931. /*  C M R E S  --  Reset pointers to beginning of command buffer.  */
  932.  
  933. VOID
  934. cmres() {
  935.     inword = 0;                /* We're not in a word */
  936.     cc = 0;                /* Character count is zero */
  937.  
  938. /* Initialize pointers */
  939.  
  940.     pp = cmdbuf;            /* Beginning of current field */
  941.     bp = cmdbuf;            /* Current position within buffer */
  942.     np = cmdbuf;            /* Where to start next field */
  943.  
  944.     cmfldflgs = 0;
  945.     cmflgs = -5;                        /* Parse not yet started. */
  946.     ungw = 0;                /* Don't need to unget a word. */
  947. }
  948.  
  949. /*  C M I N I  --  Clear the command and atom buffers, reset pointers.  */
  950.  
  951. /*
  952. The argument specifies who is to echo the user's typein --
  953.   1 means the cmd package echoes
  954.   0 somebody else (system, front end, terminal) echoes
  955. */
  956. VOID
  957. cmini(d) int d; {
  958. #ifdef DCMDBUF
  959.     if (!atmbuf)
  960.       if (cmsetup()<0)
  961.     fatal("fatal error: unable to allocate command buffers");
  962. #endif /* DCMDBUF */
  963. #ifdef USE_MEMCPY
  964.     memset(cmdbuf,0,CMDBL);
  965.     memset(atmbuf,0,ATMBL);
  966. #else
  967.     for (bp = cmdbuf; bp < cmdbuf+CMDBL; bp++) *bp = NUL;
  968.     for (bp = atmbuf; bp < atmbuf+ATMBL; bp++) *bp = NUL;
  969. #endif /* USE_MEMCPY */
  970.  
  971.     *atmbuf = *savbuf = *atxbuf = *atybuf = *filbuf = NUL;
  972.     blocklvl = 0;            /* Block level is 0 */
  973.     linebegin = 1;            /* At the beginning of a line */
  974.     dpx = d;                /* Global copy of the echo flag */
  975.     debug(F101,"cmini dpx","",dpx);
  976.     crflag = 0;                /* Reset flags */
  977.     qmflag = 0;
  978.     esflag = 0;
  979. #ifdef CK_RECALL
  980.     no_recall = 0;            /* Start out with recall enabled */
  981. #endif /* CK_RECALL */
  982.     cmres();                /* Sets bp etc */
  983.     newcmd = 1;                /* See addcmd() */
  984. }
  985.  
  986. #ifndef NOSPL
  987. /*
  988.   The following bits are to allow the command package to call itself
  989.   in the middle of a parse.  To do this, begin by calling cmpush, and
  990.   end by calling cmpop.  As you can see, this is rather expensive.
  991. */
  992. #ifdef DCMDBUF
  993. struct cmp {
  994.     int i[5];                /* stack for integers */
  995.     char *c[3];                /* stack for pointers */
  996.     char *b[8];                /* stack for buffer contents */
  997. };
  998. struct cmp *cmp = 0;
  999. #else
  1000. int cmp_i[CMDDEP+1][5];            /* Stack for integers */
  1001. char *cmp_c[CMDDEP+1][5];        /* for misc pointers */
  1002. char *cmp_b[CMDDEP+1][7];        /* for buffer contents pointers */
  1003. #endif /* DCMDBUF */
  1004.  
  1005. int cmddep = -1;            /* Current stack depth */
  1006.  
  1007. int
  1008. cmpush() {                /* Save the command environment */
  1009.     char *cp;                /* Character pointer */
  1010.  
  1011.     if (cmddep >= CMDDEP)        /* Enter a new command depth */
  1012.       return(-1);
  1013.     cmddep++;
  1014.     debug(F101,"&cmpush to depth","",cmddep);
  1015.  
  1016. #ifdef DCMDBUF
  1017.     /* allocate memory for cmp if not already done */
  1018.     if (!cmp && !(cmp = (struct cmp *) malloc(sizeof(struct cmp)*(CMDDEP+1))))
  1019.       fatal("cmpush: no memory for cmp");
  1020.     cmp[cmddep].i[0] = cmflgs;        /* First do the global ints */
  1021.     cmp[cmddep].i[1] = cmfsav;
  1022.     cmp[cmddep].i[2] = atxn;
  1023.     cmp[cmddep].i[3] = ungw;
  1024.  
  1025.     cmp[cmddep].c[0] = bp;        /* Then the global pointers */
  1026.     cmp[cmddep].c[1] = pp;
  1027.     cmp[cmddep].c[2] = np;
  1028. #else
  1029.     cmp_i[cmddep][0] = cmflgs;        /* First do the global ints */
  1030.     cmp_i[cmddep][1] = cmfsav;
  1031.     cmp_i[cmddep][2] = atxn;
  1032.     cmp_i[cmddep][3] = ungw;
  1033.  
  1034.     cmp_c[cmddep][0] = bp;        /* Then the global pointers */
  1035.     cmp_c[cmddep][1] = pp;
  1036.     cmp_c[cmddep][2] = np;
  1037. #endif /* DCMDBUF */
  1038.  
  1039.     /* Now the buffers themselves.  A lot of repititious code... */
  1040.  
  1041. #ifdef DCMDBUF
  1042.     cp = malloc((int)strlen(cmdbuf)+1);    /* 0: Command buffer */
  1043.     if (cp) strcpy(cp,cmdbuf);
  1044.     cmp[cmddep].b[0] = cp;
  1045.     if (cp == NULL) return(-1);
  1046.  
  1047.     cp = malloc((int)strlen(savbuf)+1);    /* 1: Save buffer */
  1048.     if (cp) strcpy(cp,savbuf);
  1049.     cmp[cmddep].b[1] = cp;
  1050.     if (cp == NULL) return(-1);
  1051.  
  1052.     cmp[cmddep].b[2] = NULL;
  1053.  
  1054.     cp = malloc((int)strlen(atmbuf)+1);    /* 3: Atom buffer */
  1055.     if (cp) strcpy(cp,atmbuf);
  1056.     cmp[cmddep].b[3] = cp;
  1057.     if (cp == NULL) return(-1);
  1058.  
  1059.     cp = malloc((int)strlen(atxbuf)+1);    /* 4: Expansion buffer */
  1060.     if (cp) strcpy(cp,atxbuf);
  1061.     cmp[cmddep].b[4] = cp;
  1062.     if (cp == NULL) return(-1);
  1063.  
  1064.     cp = malloc((int)strlen(atybuf)+1);    /* 5: Atom buffer copy */
  1065.     if (cp) strcpy(cp,atybuf);
  1066.     cmp[cmddep].b[5] = cp;
  1067.     if (cp == NULL) return(-1);
  1068.  
  1069.     cp = malloc((int)strlen(filbuf)+1);    /* 6: File name buffer */
  1070.     if (cp) strcpy(cp,filbuf);
  1071.     cmp[cmddep].b[6] = cp;
  1072.     if (cp == NULL) return(-1);
  1073. #else
  1074.     cp = malloc((int)strlen(cmdbuf)+1);    /* 0: Command buffer */
  1075.     if (cp) strcpy(cp,cmdbuf);
  1076.     cmp_b[cmddep][0] = cp;
  1077.     if (cp == NULL) return(-1);
  1078.  
  1079.     cp = malloc((int)strlen(savbuf)+1);    /* 1: Save buffer */
  1080.     if (cp) strcpy(cp,savbuf);
  1081.     cmp_b[cmddep][1] = cp;
  1082.     if (cp == NULL) return(-1);
  1083.  
  1084.     cmp_b[cmddep][2] = NULL;
  1085.  
  1086.     cp = malloc((int)strlen(atmbuf)+1);    /* 3: Atom buffer */
  1087.     if (cp) strcpy(cp,atmbuf);
  1088.     cmp_b[cmddep][3] = cp;
  1089.     if (cp == NULL) return(-1);
  1090.  
  1091.     cp = malloc((int)strlen(atxbuf)+1);    /* 4: Expansion buffer */
  1092.     if (cp) strcpy(cp,atxbuf);
  1093.     cmp_b[cmddep][4] = cp;
  1094.     if (cp == NULL) return(-1);
  1095.  
  1096.     cp = malloc((int)strlen(atybuf)+1);    /* 5: Atom buffer copy */
  1097.     if (cp) strcpy(cp,atybuf);
  1098.     cmp_b[cmddep][5] = cp;
  1099.     if (cp == NULL) return(-1);
  1100.  
  1101.     cp = malloc((int)strlen(filbuf)+1);    /* 6: File name buffer */
  1102.     if (cp) strcpy(cp,filbuf);
  1103.     cmp_b[cmddep][6] = cp;
  1104.     if (cp == NULL) return(-1);
  1105. #endif /* DCMDBUF */
  1106.  
  1107.     cmini(dpx);                /* Initize the command parser */
  1108.     return(0);
  1109. }
  1110.  
  1111. int
  1112. cmpop() {                /* Restore the command environment */
  1113.     if (cmddep < 0) {
  1114.     debug(F100,"&cmpop called from top level","",0);
  1115.     return(-1);            /* Don't pop too much! */
  1116.     }
  1117. #ifdef DCMDBUF
  1118.     cmflgs = cmp[cmddep].i[0];        /* First do the global ints */
  1119.     cmfsav = cmp[cmddep].i[1];
  1120.     atxn = cmp[cmddep].i[2];
  1121.     ungw = cmp[cmddep].i[3];
  1122.  
  1123.     bp = cmp[cmddep].c[0];        /* Then the global pointers */
  1124.     pp = cmp[cmddep].c[1];
  1125.     np = cmp[cmddep].c[2];
  1126. #else
  1127.     cmflgs = cmp_i[cmddep][0];        /* First do the global ints */
  1128.     cmfsav = cmp_i[cmddep][1];
  1129.     atxn = cmp_i[cmddep][2];
  1130.     ungw = cmp_i[cmddep][3];
  1131.  
  1132.     bp = cmp_c[cmddep][0];        /* Then the global pointers */
  1133.     pp = cmp_c[cmddep][1];
  1134.     np = cmp_c[cmddep][2];
  1135. #endif /* DCMDBUF */
  1136.  
  1137.     /* Now the buffers themselves. */
  1138.     /* Note: strncpy(), not ckstrncpy() -- Here we WANT the NUL padding... */
  1139.  
  1140. #ifdef DCMDBUF
  1141.     if (cmp[cmddep].b[0]) {
  1142.  
  1143.     strncpy(cmdbuf,cmp[cmddep].b[0],CMDBL); /* 0: Command buffer */
  1144.     free(cmp[cmddep].b[0]);
  1145.     cmp[cmddep].b[0] = NULL;
  1146.     }
  1147.     if (cmp[cmddep].b[1]) {
  1148.     strncpy(savbuf,cmp[cmddep].b[1],CMDBL); /* 1: Save buffer */
  1149.     free(cmp[cmddep].b[1]);
  1150.     cmp[cmddep].b[1] = NULL;
  1151.     }
  1152.     if (cmp[cmddep].b[3]) {
  1153.     strncpy(atmbuf,cmp[cmddep].b[3],ATMBL); /* 3: Atomic buffer! */
  1154.     free(cmp[cmddep].b[3]);
  1155.     cmp[cmddep].b[3] = NULL;
  1156.     }
  1157.     if (cmp[cmddep].b[4]) {
  1158.     strncpy(atxbuf,cmp[cmddep].b[4],ATMBL); /* 4: eXpansion buffer */
  1159.     free(cmp[cmddep].b[4]);
  1160.     cmp[cmddep].b[4] = NULL;
  1161.     }
  1162.     if (cmp[cmddep].b[5]) {
  1163.     strncpy(atybuf,cmp[cmddep].b[5],ATMBL); /* 5: Atom buffer copY */
  1164.     free(cmp[cmddep].b[5]);
  1165.     cmp[cmddep].b[5] = NULL;
  1166.     }
  1167.     if (cmp[cmddep].b[6]) {
  1168.     strncpy(filbuf,cmp[cmddep].b[6],ATMBL); /* 6: Filename buffer */
  1169.     free(cmp[cmddep].b[6]);
  1170.     cmp[cmddep].b[6] = NULL;
  1171.     }
  1172. #else
  1173.     if (cmp_b[cmddep][0]) {
  1174.     strncpy(cmdbuf,cmp_b[cmddep][0],CMDBL); /* 0: Command buffer */
  1175.     free(cmp_b[cmddep][0]);
  1176.     cmp_b[cmddep][0] = NULL;
  1177.     }
  1178.     if (cmp_b[cmddep][1]) {
  1179.     strncpy(savbuf,cmp_b[cmddep][1],CMDBL); /* 1: Save buffer */
  1180.     free(cmp_b[cmddep][1]);
  1181.     cmp_b[cmddep][1] = NULL;
  1182.     }
  1183.     if (cmp_b[cmddep][3]) {
  1184.     strncpy(atmbuf,cmp_b[cmddep][3],ATMBL); /* 3: Atomic buffer! */
  1185.     free(cmp_b[cmddep][3]);
  1186.     cmp_b[cmddep][3] = NULL;
  1187.     }
  1188.     if (cmp_b[cmddep][4]) {
  1189.     strncpy(atxbuf,cmp_b[cmddep][4],ATMBL); /* 4: eXpansion buffer */
  1190.     free(cmp_b[cmddep][4]);
  1191.     cmp_b[cmddep][4] = NULL;
  1192.     }
  1193.     if (cmp_b[cmddep][5]) {
  1194.     strncpy(atybuf,cmp_b[cmddep][5],ATMBL); /* 5: Atom buffer copY */
  1195.     free(cmp_b[cmddep][5]);
  1196.     cmp_b[cmddep][5] = NULL;
  1197.     }
  1198.     if (cmp_b[cmddep][6]) {
  1199.     strncpy(filbuf,cmp_b[cmddep][6],ATMBL); /* 6: Filename buffer */
  1200.     free(cmp_b[cmddep][6]);
  1201.     cmp_b[cmddep][6] = NULL;
  1202.     }
  1203. #endif /* DCMDBUF */
  1204.  
  1205.     cmddep--;                /* Rise, rise */
  1206.     debug(F101,"&cmpop to depth","",cmddep);
  1207.     return(cmddep);
  1208. }
  1209. #endif /* NOSPL */
  1210.  
  1211. #ifdef COMMENT
  1212. VOID                    /* Not used */
  1213. stripq(s) char *s; {                    /* Function to strip '\' quotes */
  1214.     char *t;
  1215.     while (*s) {
  1216.         if (*s == CMDQ) {
  1217.             for (t = s; *t != '\0'; t++) *t = *(t+1);
  1218.         }
  1219.         s++;
  1220.     }
  1221. }
  1222. #endif /* COMMENT */
  1223.  
  1224. /* Convert tabs to spaces, one for one */
  1225. VOID
  1226. untab(s) char *s; {
  1227.     while (*s) {
  1228.     if (*s == HT) *s = SP;
  1229.     s++;
  1230.     }
  1231. }
  1232.  
  1233. /*  C M N U M  --  Parse a number in the indicated radix  */
  1234.  
  1235. /*
  1236.  The radix is specified in the arg list.
  1237.  Parses unquoted numeric strings in the given radix.
  1238.  Parses backslash-quoted numbers in the radix indicated by the quote:
  1239.    \nnn = \dnnn = decimal, \onnn = octal, \xnn = Hexadecimal.
  1240.  If these fail, then if a preprocessing function is supplied, that is applied
  1241.  and then a second attempt is made to parse an unquoted decimal string.
  1242.  And if that fails, the preprocessed string is passed to an arithmetic
  1243.  expression evaluator.
  1244.  
  1245.  Returns:
  1246.    -3 if no input present when required,
  1247.    -2 if user typed an illegal number,
  1248.    -1 if reparse needed,
  1249.     0 otherwise, with argument n set to the number that was parsed
  1250. */
  1251. /* This is the traditional cmnum() that gets an int */
  1252. int
  1253. cmnum(xhlp,xdef,radix,n,f) char *xhlp, *xdef; int radix, *n; xx_strp f; {
  1254.     CK_OFF_T z = (CK_OFF_T)0, check;
  1255.     int x;
  1256.     x = cmnumw(xhlp,xdef,radix,&z,f);
  1257.     *n = z;
  1258.     check = *n;
  1259.     if (check != z) {
  1260.     printf("?Magnitude of result too large for integer - %s\n",ckfstoa(z));
  1261.     return(-9);
  1262.     }
  1263.     return(x);
  1264. }
  1265.  
  1266. /*
  1267.   This is the new cmnum() that gets a "wide" result, whatever CK_OFF_T
  1268.   is defined to be, normally 32 or 64 bits, depending on the platform.
  1269.   fdc, 24 Dec 2005.
  1270. */
  1271. int
  1272. cmnumw(xhlp,xdef,radix,n,f)
  1273.     char *xhlp, *xdef; int radix; CK_OFF_T *n; xx_strp f; {
  1274.     int x; char *s, *zp, *zq;
  1275. #ifdef COMMENT
  1276.     char lbrace, rbrace;
  1277. #endif /* COMMENT */
  1278.  
  1279.     if (!xhlp) xhlp = "";
  1280.     if (!xdef) xdef = "";
  1281.  
  1282. #ifdef COMMENT
  1283.     if (cmfldflgs & 1) {
  1284.     lbrace = '(';
  1285.     rbrace = ')';
  1286.     } else {
  1287.     lbrace = '{';
  1288.     rbrace = '}';
  1289.     }
  1290. #endif /* COMMENT */
  1291.  
  1292.     if (radix != 10 && radix != 8) {    /* Just do bases 8 and 10 */
  1293.         printf("cmnum: illegal radix - %d\n",radix);
  1294.         return(-2);
  1295.     } /* Easy to add others but there has never been a need for it. */
  1296.     x = cmfld(xhlp,xdef,&s,(xx_strp)0);
  1297.     debug(F101,"cmnum: cmfld","",x);
  1298.     if (x < 0) return(x);        /* Parse a field */
  1299.     zp = atmbuf;
  1300. /*
  1301.   Edit 192 - Allow any number field to be braced.  This lets us include
  1302.   spaces in expressions, but perhaps more important lets us have user-defined
  1303.   functions in numeric fields.
  1304. */
  1305.     zp = brstrip(zp);            /* Strip braces */
  1306.     if (cmfldflgs & 1 && *zp == '(') {    /* Parens too.. */
  1307.     x = (int) strlen(atmbuf);
  1308.     if (x > 0) {
  1309.         if (*(atmbuf+x-1) == ')') {
  1310.         *(atmbuf+x-1) = NUL;
  1311.         zp++;
  1312.         }
  1313.     }
  1314.     }
  1315.     if (chknum(zp)) {            /* Check for number */
  1316.     if (radix == 8) {        /* If it's supposed to be octal */
  1317.         zp = ckradix(zp,8,10);    /* convert to decimal */
  1318.         if (!zp) return(-2);
  1319.         if (!strcmp(zp,"-1")) return(-2);
  1320.     }
  1321.     errno = 0;            /* Got one, we're done. */
  1322.         *n = ckatofs(zp);
  1323.     if (errno) {
  1324.         perror(zp);
  1325.         return(-9);
  1326.     }
  1327.     debug(F101,"cmnum 1st chknum ok","",*n);
  1328.         return(0);
  1329.     } else if ((x = xxesc(&zp)) > -1) {    /* Check for backslash escape */
  1330.  
  1331. #ifndef OS2
  1332.     *n = x;
  1333. #else
  1334.     *n = wideresult;
  1335. #endif /* OS2 */
  1336.  
  1337.     debug(F101,"cmnum xxesc ok","",*n);
  1338.     return(*zp ? -2 : 0);
  1339.     } else if (f) {            /* If conversion function given */
  1340.     zq = atxbuf;            /* Try that */
  1341.     atxn = CMDBL;
  1342.     if ((*f)(zp,&zq,&atxn) < 0)    /* Convert */
  1343.       return(-2);
  1344.     zp = atxbuf;
  1345.     }
  1346.     debug(F110,"cmnum zp 1",zp,0);
  1347.     if (!*zp) zp = xdef;        /* Result empty, substitute default */
  1348.     debug(F110,"cmnum zp 2",zp,0);
  1349.     if (chknum(zp)) {            /* Check again for decimal number */
  1350.     if (radix == 8) {        /* If it's supposed to be octal */
  1351.         zp = ckradix(zp,8,10);    /* convert to decimal */
  1352.         if (!zp) return(-2);
  1353.         if (!strcmp(zp,"-1")) return(-2);
  1354.     }
  1355.     errno = 0;
  1356.         *n = ckatofs(zp);
  1357.     if (errno) {
  1358.         perror(zp);
  1359.         return(-9);
  1360.     }
  1361.     debug(F101,"cmnum 2nd chknum ok","",*n);
  1362.         return(0);
  1363. #ifndef NOSPL
  1364.     }  else if ((x = xxesc(&zp)) > -1) { /* Check for backslash escape */
  1365. #ifndef OS2
  1366.     *n = x;
  1367. #else
  1368.     *n = wideresult;
  1369. #endif /* OS2 */
  1370.     debug(F101,"cmnum xxesc 2 ok","",*n);
  1371.     return(*zp ? -2 : 0);
  1372.     } else if (f) {            /* Not numeric, maybe an expression */
  1373.     char * p;
  1374.     p = evala(zp);
  1375.     if (chknum(p)) {
  1376.         if (radix == 8) {        /* If it's supposed to be octal */
  1377.         zp = ckradix(zp,8,10);    /* convert to decimal */
  1378.         if (!zp) return(-2);
  1379.         if (!strcmp(zp,"-1")) return(-2);
  1380.         }
  1381.         errno = 0;
  1382.         *n = ckatofs(p);
  1383.         if (errno) {
  1384.         perror(p);
  1385.         return(-9);
  1386.         }
  1387.         debug(F101,"cmnum exp eval ok","",*n);
  1388.         return(0);
  1389.     } else return(-2);
  1390. #endif /* NOSPL */
  1391.     } else {                /* Not numeric */
  1392.     return(-2);
  1393.     }
  1394. }
  1395.  
  1396. #ifdef CKCHANNELIO
  1397. extern int z_error;
  1398. #endif /* CKCHANNELIO */
  1399.  
  1400. /*  C M O F I  --  Parse the name of an output file  */
  1401.  
  1402. /*
  1403.  Depends on the external function zchko(); if zchko() not available, use
  1404.  cmfld() to parse output file names.
  1405.  
  1406.  Returns:
  1407.    -9 like -2, except message already printed,
  1408.    -3 if no input present when required,
  1409.    -2 if permission would be denied to create the file,
  1410.    -1 if reparse needed,
  1411.     0 or 1 if file can be created, with xp pointing to name.
  1412.     2 if given the name of an existing directory.
  1413. */
  1414. int
  1415. cmofi(xhlp,xdef,xp,f) char *xhlp, *xdef, **xp; xx_strp f; {
  1416.     int x; char *s, *zq;
  1417. #ifdef DOCHKVAR
  1418.     int tries;
  1419. #endif /* DOCHKVAR */
  1420. #ifdef DTILDE
  1421.     char *dirp;
  1422. #endif /* DTILDE */
  1423.  
  1424.     cmfldflgs = 0;
  1425.  
  1426.     if (!xhlp) xhlp = "";
  1427.     if (!xdef) xdef = "";
  1428.  
  1429.     if (*xhlp == NUL) xhlp = "Output file";
  1430.     *xp = "";
  1431.  
  1432.     debug(F110,"cmofi xdef",xdef,0);
  1433.     x = cmfld(xhlp,xdef,&s,(xx_strp)0);
  1434.     debug(F111,"cmofi cmfld returns",s,x);
  1435.     if (x < 0)
  1436.       return(x);
  1437.  
  1438.     s = brstrip(s);            /* Strip enclosing braces */
  1439.     debug(F110,"cmofi 1.5",s,0);
  1440.  
  1441. #ifdef DOCHKVAR
  1442.     tries = 0;
  1443.     {
  1444.     char *p = s;
  1445.     /*
  1446.       This is really ugly.  If we skip conversion the first time through,
  1447.       then variable names like \%a will be used as filenames (e.g. creating
  1448.       a file called %A in the root directory).  If we DON'T skip conversion
  1449.       the first time through, then single backslashes used as directory
  1450.       separators in filenames will be misinterpreted as variable lead-ins.
  1451.       So we prescan to see if it has any variable references.  But this
  1452.       module is not supposed to know anything about variables, functions,
  1453.       etc, so this code does not really belong here, but rather it should
  1454.       be at the same level as zzstring().
  1455.     */
  1456. /*
  1457.   Hmmm, this looks a lot like chkvar() except it that includes \nnn number
  1458.   escapes.  But why?  This makes commands like "mkdir c:\123" impossible.
  1459.   And in fact, "mkdir c:\123" creates a directory called "c:{".  What's worse,
  1460.   rmdir(), which *does* call chkvar(), won't let us remove it.  So let's at
  1461.   least try making cmofi() symmetrical with cmifi()...
  1462. */
  1463. #ifdef COMMENT
  1464.     char * q;
  1465.     while ( (tries == 0) && (p = strchr(p,CMDQ)) ) {
  1466.         q = *(p+1);            /* Char after backslash */
  1467.         if (!q)            /* None, quit */
  1468.           break;
  1469.         if (isupper(q))        /* If letter, convert to lowercase */
  1470.           q = tolower(q);
  1471.         if (isdigit(q)) {        /* If it's a digit, */
  1472.         tries = 1;        /* assume it's a backslash code  */
  1473.         break;
  1474.         }
  1475.         switch (q) {
  1476.           case CMDQ:        /* Double backslash */
  1477.         tries = 1;        /* so call the conversion function */
  1478.         break;
  1479.           case '%':            /* Variable or array reference */
  1480.           case '&':            /* must be followed by letter */
  1481.         if (isalpha(*(p+2)) || (*(p+2) >= '0' && *(p+2) <= '9'))
  1482.           tries = 1;
  1483.         break;
  1484.           case 'm': case 'v': case '$': /* \m(), \v(), \$() */
  1485.         if (*(p+2) == '(')
  1486.           if (strchr(p+2,')'))
  1487.             tries = 1;
  1488.         break;
  1489.           case 'f':            /* \Fname() */
  1490.         if (strchr(p+2,'('))
  1491.           if (strchr(p+2,')'))
  1492.               tries = 1;
  1493.         break;
  1494.           case '{':            /* \{...} */
  1495.         if (strchr(p+2,'}'))
  1496.           tries = 1;
  1497.         break;
  1498.           case 'd': case 'o':    /* Decimal or Octal number */
  1499.             if (isdigit(*(p+2)))
  1500.           tries = 1;
  1501.         break;
  1502.           case 'x':            /* Hex number */
  1503.         if (isdigit(*(p+2)) ||
  1504.             ((*(p+2) >= 'a' && *(p+2) <= 'f') ||
  1505.              ((*(p+2) >= 'A' && *(p+2) <= 'F'))))
  1506.           tries = 1;
  1507.           default:
  1508.         break;
  1509.         }
  1510.         p++;
  1511.     }
  1512. #else
  1513. #ifndef NOSPL
  1514.     if (f) {            /* If a conversion function is given */
  1515.         char *s = p;        /* See if there are any variables in */
  1516.         while (*s) {        /* the string and if so, expand them */
  1517.         if (chkvar(s)) {
  1518.             tries = 1;
  1519.             break;
  1520.         }
  1521.         s++;
  1522.         }
  1523.     }
  1524. #endif /* NOSPL */
  1525. #endif /* COMMENT */
  1526.     }
  1527. #ifdef OS2
  1528. o_again:
  1529. #endif /* OS2 */
  1530.     if (tries == 1)
  1531. #endif /* DOCHKVAR */
  1532.     if (f) {                /* If a conversion function is given */
  1533.     zq = atxbuf;            /* do the conversion. */
  1534.     atxn = CMDBL;
  1535.     if ((x = (*f)(s,&zq,&atxn)) < 0)
  1536.       return(-2);
  1537.     s = atxbuf;
  1538.     if (!*s)            /* Result empty, substitute default */
  1539.       s = xdef;
  1540.     }
  1541.     debug(F111,"cmofi 2",s,x);
  1542.  
  1543. #ifdef DTILDE
  1544.     dirp = tilde_expand(s);        /* Expand tilde, if any, */
  1545.     if (*dirp != '\0') {        /* right in the atom buffer. */
  1546.     if (setatm(dirp,1) < 0) {
  1547.         printf("?Name too long\n");
  1548.         return(-9);
  1549.     }
  1550.     }
  1551.     s = atmbuf;
  1552.     debug(F110,"cmofi 3",s,0);
  1553. #endif /* DTILDE */
  1554.  
  1555.     if (iswild(s)) {
  1556.         printf("?Wildcards not allowed - %s\n",s);
  1557.         return(-2);
  1558.     }
  1559.     debug(F110,"cmofi 4",s,0);
  1560.  
  1561. #ifdef CK_TMPDIR
  1562.     /* isdir() function required for this! */
  1563.     if (isdir(s)) {
  1564.     debug(F110,"cmofi 5: is directory",s,0);
  1565.         *xp = s;
  1566.     return(2);
  1567.     }
  1568. #endif /* CK_TMPDIR */
  1569.  
  1570.     if (strcmp(s,CTTNAM) && (zchko(s) < 0)) { /* OK to write to console */
  1571. #ifdef COMMENT
  1572. #ifdef OS2
  1573. /*
  1574.   We don't try again because we already prescanned the string to see if
  1575.   if it contained anything that could be used by zzstring().
  1576. */
  1577.     if (tries++ < 1)
  1578.       goto o_again;
  1579. #endif /* OS2 */
  1580. #endif /* COMMENT */
  1581. /*
  1582.   Note: there are certain circumstances where zchko() can give a false
  1583.   positive, so don't rely on it to catch every conceivable situation in
  1584.   which the given output file can't be created.  In other words, we print
  1585.   a message and fail here if we KNOW the file can't be created.  If we
  1586.   succeed but the file can't be opened, the code that tries to open the file
  1587.   has to print a message.
  1588. */
  1589.     debug(F110,"cmofi 6: failure",s,0);
  1590. #ifdef CKROOT
  1591.     if (ckrooterr)
  1592.       printf("?Off Limits: %s\n",s);
  1593.     else
  1594. #endif /* CKROOT */
  1595.       printf("?Write permission denied - %s\n",s);
  1596. #ifdef CKCHANNELIO
  1597.     z_error = FX_ACC;
  1598. #endif /* CKCHANNELIO */
  1599.         return(-9);
  1600.     } else {
  1601.     debug(F110,"cmofi 7: ok",s,0);
  1602.         *xp = s;
  1603.         return(x);
  1604.     }
  1605. }
  1606.  
  1607. /*  C M I F I  --  Parse the name of an existing file  */
  1608.  
  1609. /*
  1610.  This function depends on the external functions:
  1611.    zchki()  - Check if input file exists and is readable.
  1612.    zxpand() - Expand a wild file specification into a list.
  1613.    znext()  - Return next file name from list.
  1614.  If these functions aren't available, then use cmfld() to parse filenames.
  1615. */
  1616. /*
  1617.  Returns
  1618.    -4 EOF
  1619.    -3 if no input present when required,
  1620.    -2 if file does not exist or is not readable,
  1621.    -1 if reparse needed,
  1622.     0 or 1 otherwise, with:
  1623.         xp pointing to name,
  1624.         wild = 1 if name contains '*' or '?', 0 otherwise.
  1625. */
  1626.  
  1627. #ifdef COMMENT /* This horrible hack has been replaced - see further down */
  1628. /*
  1629.    C M I O F I  --  Parse an input file OR the name of a nonexistent file.
  1630.  
  1631.    Use this when an existing file is wanted (so we get help, completion, etc),
  1632.    but if a file of the given name does not exist, the name of a new file is
  1633.    accepted.  For example, with the EDIT command (edit an existing file, or
  1634.    create a new file).  Returns -9 if file does not exist.  It is up to the
  1635.    caller to check creatability.
  1636. */
  1637. static int nomsg = 0;
  1638. int
  1639. cmiofi(xhlp,xdef,xp,wild,f) char *xhlp, *xdef, **xp; int *wild; xx_strp f; {
  1640.     int msgsave, x;
  1641.     msgsave = nomsg;
  1642.     nomsg = 1;
  1643.     x = cmifi2(xhlp,xdef,xp,wild,0,NULL,f,0);
  1644.     nomsg = msgsave;
  1645.     return(x);
  1646. }
  1647. #endif    /* COMMENT */
  1648.  
  1649. int
  1650. cmifi(xhlp,xdef,xp,wild,f) char *xhlp, *xdef, **xp; int *wild; xx_strp f; {
  1651.     return(cmifi2(xhlp,xdef,xp,wild,0,NULL,f,0));
  1652. }
  1653. /*
  1654.   cmifip() is called when we want to supply a path or path list to search
  1655.   in case the filename that the user gives is (a) not absolute, and (b) can't
  1656.   be found as given.  The path string can be the name of a single directory,
  1657.   or a list of directories separated by the PATHSEP character, defined in
  1658.   ckucmd.h.  Look in ckuusr.c and ckuus3.c for examples of usage.
  1659. */
  1660. int
  1661. cmifip(xhlp,xdef,xp,wild,d,path,f)
  1662.     char *xhlp,*xdef,**xp; int *wild, d; char * path; xx_strp f; {
  1663.     return(cmifi2(xhlp,xdef,xp,wild,0,path,f,0));
  1664. }
  1665.  
  1666. /*  C M D I R  --  Parse a directory name  */
  1667.  
  1668. /*
  1669.  This function depends on the external functions:
  1670.    isdir(s)  - Check if string s is the name of a directory
  1671.    zchki(s)  - Check if input file s exists and what type it is.
  1672.  If these functions aren't available, then use cmfld() to parse dir names.
  1673.  
  1674.  Returns
  1675.    -9 For all sorts of reasons, after printing appropriate error message.
  1676.    -4 EOF
  1677.    -3 if no input present when required,
  1678.    -2 if out of space or other internal error,
  1679.    -1 if reparse needed,
  1680.     0 or 1, with xp pointing to name, if directory specified,
  1681. */
  1682. int
  1683. cmdir(xhlp,xdef,xp,f) char *xhlp, *xdef, **xp; xx_strp f; {
  1684.     int wild;
  1685.     return(cmifi2(xhlp,xdef,xp,&wild,0,NULL,f,1));
  1686. }
  1687.  
  1688. /* Like CMDIR but includes PATH search */
  1689.  
  1690. int
  1691. cmdirp(xhlp,xdef,xp,path,f) char *xhlp, *xdef, **xp; char * path; xx_strp f; {
  1692.     int wild;
  1693.     return(cmifi2(xhlp,xdef,xp,&wild,0,path,f,1));
  1694. }
  1695.  
  1696. /*
  1697.   cmifi2() is the base filename parser called by cmifi, cmifip, cmdir, etc.
  1698.   Use it directly when you also want to parse a directory or device
  1699.   name as an input file, as in the DIRECTORY command.  Call with:
  1700.     xhlp  -- help message on ?
  1701.     xdef  -- default response
  1702.     xp    -- pointer to result (in our space, must be copied from here)
  1703.     wild  -- flag set upon return to indicate if filespec was wild
  1704.     d     -- 0 to parse files, 1 to parse files or directories
  1705.              Add 2 to inhibit following of symlinks.
  1706.     path  -- search path for files
  1707.     f     -- pointer to string processing function (e.g. to evaluate variables)
  1708.     dirflg -- 1 to parse *only* directories, 0 otherwise
  1709. */
  1710. int
  1711. cmifi2(xhlp,xdef,xp,wild,d,path,f,dirflg)
  1712.     char *xhlp,*xdef,**xp; int *wild, d; char * path; xx_strp f; int dirflg; {
  1713.     extern int recursive, diractive, cdactive, dblquo;
  1714.     int i, x, itsadir, xc, expanded = 0, nfiles = 0, children = -1;
  1715.     int qflag = 0;
  1716.     long y;
  1717.     CK_OFF_T filesize;
  1718.     char *sp = NULL, *zq, *np = NULL;
  1719.     char *sv = NULL, *p = NULL;
  1720. #ifdef DTILDE
  1721.     char *dirp;
  1722. #endif /* DTILDE */
  1723.  
  1724. #ifndef NOPARTIAL
  1725. #ifndef OS2
  1726. #ifdef OSK
  1727.     /* This large array is dynamic for OS-9 -- should do for others too... */
  1728.     extern char **mtchs;
  1729. #else
  1730. #ifdef UNIX
  1731.     /* OK, for UNIX too */
  1732.     extern char **mtchs;
  1733. #else
  1734. #ifdef VMS
  1735.     extern char **mtchs;
  1736. #else
  1737.     extern char *mtchs[];
  1738. #endif /* VMS */
  1739. #endif /* UNIX */
  1740. #endif /* OSK */
  1741. #endif /* OS2 */
  1742. #endif /* NOPARTIAL */
  1743.  
  1744.     if (!xhlp) xhlp = "";
  1745.     if (!xdef) xdef = "";
  1746.  
  1747. #ifndef NOLASTFILE
  1748.     makestr(&tmplastfile,NULL);
  1749. #endif    /* NOLASTFILE */
  1750.     nzxopts = 0;            /* zxpand() options */
  1751.     debug(F101,"cmifi d","",d);
  1752.     if (d & 2) {            /* d & 2 means don't follow symlinks */
  1753.     d ^= 2;
  1754.     nzxopts = ZX_NOLINKS;
  1755.     }
  1756.     debug(F101,"cmifi nzxopts","",nzxopts);
  1757.     cmfldflgs = 0;
  1758.     if (path)
  1759.       if (!*path)
  1760.     path = NULL;
  1761.     if (path) {                /* Make a copy we can poke */
  1762.     x = strlen(path);
  1763.     np = (char *) malloc(x + 1);
  1764.     if (np) {
  1765.         strcpy(np, path);
  1766.         path = sp = np;
  1767.     }
  1768.     }
  1769.     debug(F110,"cmifi2 path",path,0);
  1770.  
  1771.     ckstrncpy(cmdefault,xdef,CMDEFAULT); /* Copy default */
  1772.     xdef = cmdefault;
  1773.  
  1774.     inword = 0;                /* Initialize counts & pointers */
  1775.     cc = 0;
  1776.     xc = 0;
  1777.     *xp = "";                /* Pointer to result string */
  1778.     if ((x = cmflgs) != 1) {            /* Already confirmed? */
  1779. #ifdef BS_DIRSEP
  1780.     dirnamflg = 1;
  1781.         x = gtword(0);            /* No, get a word */
  1782.     dirnamflg = 0;
  1783. #else
  1784.         x = gtword(0);                  /* No, get a word */
  1785. #endif /* BS_DIRSEP */
  1786.     } else {                /* If so, use default, if any. */
  1787.         if (setatm(xdef,1) < 0) {
  1788.         printf("?Default name too long\n");
  1789.         if (np) free(np);
  1790.         return(-9);
  1791.     }
  1792.     }
  1793.   i_path:
  1794.     *xp = atmbuf;                       /* Point to result. */
  1795.  
  1796.     while (1) {
  1797.         xc += cc;                       /* Count this character. */
  1798.         debug(F111,"cmifi gtword",atmbuf,xc);
  1799.     debug(F101,"cmifi switch x","",x);
  1800.         switch (x) {            /* x = gtword() return code */
  1801.       case -10:
  1802.         if (gtimer() > timelimit) {
  1803. #ifdef IKSD
  1804.                 if (inserver) {
  1805.                     printf("\r\nIKSD IDLE TIMEOUT: %d sec\r\n", timelimit);
  1806.                     doexit(GOOD_EXIT,0);
  1807.                 }
  1808. #endif /* IKSD */
  1809.         /* if (!quiet) printf("?Timed out\n"); */
  1810.         return(-10);
  1811.         } else {
  1812.         x = gtword(0);
  1813.         continue;
  1814.         }
  1815.       case -9:
  1816.         printf("Command or field too long\n");
  1817.       case -4:            /* EOF */
  1818.       case -2:            /* Out of space. */
  1819.       case -1:            /* Reparse needed */
  1820.         if (np) free(np);
  1821.         return(x);
  1822.       case 1:            /* CR */
  1823.       case 0:            /* SP */
  1824.         if (xc == 0)        /* If no input... */
  1825.           *xp = xdef;        /* substitute the default */
  1826. #ifndef NOLASTFILE
  1827.         makestr(&tmplastfile,*xp);    /* Make a copy before bstripping */
  1828. #endif    /* #ifndef NOLASTFILE */
  1829.         *xp = brstrip(*xp);        /* Strip braces */
  1830.         if (**xp == NUL) {        /* 12 mar 2001 */
  1831.         if (np) free(np);
  1832.         return(-3);
  1833.         }
  1834.         debug(F110,"cmifi brstrip",*xp,0);
  1835. #ifndef NOSPL
  1836.         if (f) {            /* If a conversion function is given */
  1837. #ifdef DOCHKVAR
  1838.         char *s = *xp;        /* See if there are any variables in */
  1839.         int x;
  1840.         while (*s) {        /* the string and if so, expand them */
  1841.             x = chkvar(s);
  1842.             /* debug(F111,"cmifi chkvar",*xp,x); */
  1843.             if (x) {
  1844. #endif /* DOCHKVAR */
  1845.             zq = atxbuf;
  1846.             atxn = CMDBL;
  1847.             if ((*f)(*xp,&zq,&atxn) < 0) {
  1848.                 if (np) free(np);
  1849.                 return(-2);
  1850.             }
  1851.             *xp = atxbuf;
  1852.             if (!atxbuf[0])
  1853.               *xp = xdef;
  1854. #ifdef DOCHKVAR
  1855.             break;
  1856.             }
  1857.             s++;
  1858.         }
  1859. #endif /* DOCHKVAR */
  1860.         }
  1861. #endif /* NOSPL */
  1862.         if (**xp == NUL) {        /* 12 mar 2001 */
  1863.         if (np) free(np);
  1864.         return(-3);
  1865.         }
  1866. #ifdef DTILDE
  1867.         if (dirflg) {
  1868.         dirp = tilde_expand(*xp); /* Expand tilde, if any, */
  1869.         if (*dirp != '\0') {    /* in the atom buffer. */
  1870.             if (setatm(dirp,1) < 0) {
  1871.             printf("Expanded name too long\n");
  1872.             if (np) free(np);
  1873.             return(-9);
  1874.             }
  1875.         }
  1876.         *xp = atmbuf;
  1877.         debug(F110,"cmifi tilde_expand",*xp,0);
  1878.         }
  1879. #endif /* DTILDE */
  1880.         if (!sv) {            /* Only do this once */
  1881.         sv = malloc((int)strlen(*xp)+1); /* Make a safe copy */
  1882.         if (!sv) {
  1883.             printf("?cmifi: malloc error\n");
  1884.             if (np) free(np);
  1885.             return(-9);
  1886.         }
  1887.         strcpy(sv,*xp);
  1888.         debug(F110,"cmifi sv",sv,0);
  1889.         }
  1890.  
  1891. /* This is to get around "cd /" failing because "too many directories match" */
  1892.  
  1893.         expanded = 0;        /* Didn't call zxpand */
  1894. #ifdef datageneral
  1895.         debug(F110,"cmifi isdir 1",*xp,0);
  1896.         {
  1897.         int y; char *s;
  1898.         s = *xp;
  1899.         y = strlen(s);
  1900.         if (y > 1 &&
  1901.             (s[y-1] == ':' ||
  1902.              s[y-1] == '^' ||
  1903.              s[y-1] == '=')
  1904.             )
  1905.           s[y-1] = NUL;
  1906.         }
  1907.         debug(F110,"cmifi isdir 2",*xp,0);
  1908. #endif /*  datageneral */
  1909.  
  1910. #ifdef VMS
  1911.         if (dirflg) {
  1912.         if (!strcmp(*xp,"..")) { /* For UNIXers... */
  1913.             setatm("-",0);
  1914.             *xp = atmbuf;
  1915.         } else if (!strcmp(*xp,".")) {
  1916.             setatm("[]",0);
  1917.             *xp = atmbuf;
  1918.         }
  1919.         }
  1920. #endif /* VMS */
  1921.         itsadir = isdir(*xp);    /* Is it a directory? */
  1922.         debug(F111,"cmifi itsadir",*xp,itsadir);
  1923. #ifdef VMS
  1924.         /* If they said "blah" where "blah.dir" is a directory... */
  1925.         /* change it to [.blah]. */
  1926.         if (!itsadir) {
  1927.         char tmpbuf[600];
  1928.         int flag = 0; char c, * p;
  1929.         p = *xp;
  1930.         while ((c = *p++) && !flag)
  1931.           if (ckstrchr(".[]:*?<>",c))
  1932.             flag = 1;
  1933.         debug(F111,"cmifi VMS dirname flag",*xp,flag);
  1934.         if (!flag) {
  1935.             ckmakmsg(tmpbuf,TMPBUFSIZ,"[.",*xp,"]",NULL);
  1936.             itsadir = isdir(tmpbuf);
  1937.             if (itsadir) {
  1938.             setatm(tmpbuf,0);
  1939.             *xp = atmbuf;
  1940.             }
  1941.             debug(F111,"cmifi VMS dirname flag itsadir",*xp,itsadir);
  1942.         }
  1943.         } else if (itsadir == 1 && *(xp[0]) == '.' && *(xp[1])) {
  1944.         char *p;
  1945.         if (p = malloc(cc + 4)) {
  1946.             ckmakmsg(p,cc+4,"[",*xp,"]",NULL);
  1947.             setatm(p,0);
  1948.             *xp = atmbuf;
  1949.             debug(F110,"cmdir .foo",*xp,0);
  1950.             free(p);
  1951.         }
  1952.         } else if (itsadir == 2 && !diractive) {
  1953.         int x;            /* [FOO]BAR.DIR instead of [FOO.BAR] */
  1954.         char *p;
  1955.         p = malloc(cc + 4);
  1956.         if (p) {
  1957.             x = cvtdir(*xp,p,ATMBL); /* Convert to [FOO.BAR] */
  1958.             if (x > 0) {
  1959.             setatm(p,0);
  1960.             *xp = atmbuf;
  1961.             debug(F110,"cmdir cvtdir",*xp,0);
  1962.             }
  1963.             free(p);
  1964.         }
  1965.         }
  1966. #endif /* VMS */
  1967.  
  1968.         debug(F101,"cmifi dirflg","",dirflg);
  1969.         if (dirflg) {        /* Parsing a directory name? */
  1970.         /* Yes, does it contain wildcards? */
  1971.         if (iswild(*xp) ||
  1972.             (diractive && (!strcmp(*xp,".")  || !strcmp(*xp,"..")))
  1973.             ) {
  1974.             nzxopts |= ZX_DIRONLY; /* Match only directory names */
  1975.             if (matchdot)  nzxopts |= ZX_MATCHDOT;
  1976.             if (recursive) nzxopts |= ZX_RECURSE;
  1977.             debug(F111,"cmifi nzxopts 2",*xp,nzxopts);
  1978.             y = nzxpand(*xp,nzxopts);
  1979.             debug(F111,"cmifi nzxpand 2",*xp,y);
  1980.             nfiles = y;
  1981.             expanded = 1;
  1982.         } else {
  1983. #ifdef VMS
  1984. /*
  1985.   This is to allow (e.g.) "cd foo", where FOO.DIR;1 is in the
  1986.   current directory.
  1987. */
  1988.             debug(F111,"cmdir itsadir",*xp,itsadir);
  1989.             if (!itsadir) {
  1990.             char *s;
  1991.             int n;
  1992.             s = *xp;
  1993.             n = strlen(s);
  1994.             if (n > 0 &&
  1995. #ifdef COMMENT
  1996.                 *s != '[' && s[n-1] != ']' &&
  1997.                 *s != '<' && s[n-1] != '>' &&
  1998. #else
  1999.                 ckindex("[",s,0,0,1) == 0 &&
  2000.                 ckindex("<",s,0,0,1) == 0 &&
  2001. #endif /* COMMENT */
  2002.                 s[n-1] != ':') {
  2003.                 char * dirbuf = NULL;
  2004.                 dirbuf = (char *)malloc(n+4);
  2005.                 if (dirbuf) {
  2006.                 if (*s == '.')
  2007.                   ckmakmsg(dirbuf,n+4,"[",s,"]",NULL);
  2008.                 else
  2009.                   ckmakmsg(dirbuf,n+4,"[.",s,"]",NULL);
  2010.                 itsadir = isdir(dirbuf);
  2011.                 debug(F111,"cmdir dirbuf",dirbuf,itsadir);
  2012.                 if (itsadir) {
  2013.                     setatm(dirbuf,0);
  2014.                     *xp = atmbuf;
  2015.                     debug(F110,"cmdir new *xp",*xp,0);
  2016.                 }
  2017.                 free(dirbuf);
  2018.                 }
  2019.  
  2020. /* This is to allow CDPATH to work in VMS... */
  2021.  
  2022.             } else if (n > 0) {
  2023.                 char * p; int i, j, k, d;
  2024.                 char rb[2] = "]";
  2025.                 if (p = malloc(x + 8)) {
  2026.                 ckstrncpy(p,*xp,x+8);
  2027.                 i = ckindex(".",p,-1,1,1);
  2028.                 d = ckindex(".dir",p,0,0,0);
  2029.                 j = ckindex("]",p,-1,1,1);
  2030.                 if (j == 0) {
  2031.                     j = ckindex(">",p,-1,1,1);
  2032.                     rb[0] = '>';
  2033.                 }
  2034.                 k = ckindex(":",p,-1,1,1);
  2035.                 if (i < j || i < k) i = 0;
  2036.                 if (d < j || d < k) d = 0;
  2037.                 /* Change [FOO]BAR or [FOO]BAR.DIR */
  2038.                 /* to [FOO.BAR] */
  2039.                 if (j > 0 && j < n) {
  2040.                     p[j-1] = '.';
  2041.                     if (d > 0) p[d-1] = NUL;
  2042.                     ckstrncat(p,rb,x+8);
  2043.                     debug(F110,"cmdir xxx",p,0);
  2044.                 }
  2045.                 itsadir = isdir(p);
  2046.                 debug(F111,"cmdir p",p,itsadir);
  2047.                 if (itsadir) {
  2048.                     setatm(p,0);
  2049.                     *xp = atmbuf;
  2050.                     debug(F110,"cmdir new *xp",*xp,0);
  2051.                 }
  2052.                 free(p);
  2053.                 }
  2054.             }
  2055.             }
  2056. #endif /* VMS */
  2057.             y = (!itsadir) ? 0 : 1;
  2058.             debug(F111,"cmifi y itsadir",*xp,y);
  2059.         }
  2060.         } else {            /* Parsing a filename. */
  2061.         debug(F110,"cmifi *xp pre-zxpand",*xp,0);
  2062. #ifndef COMMENT
  2063.         nzxopts |= (d == 0) ? ZX_FILONLY : 0; /* So always expand. */
  2064.         if (matchdot)  nzxopts |= ZX_MATCHDOT;
  2065.         if (recursive) nzxopts |= ZX_RECURSE;
  2066.         y = nzxpand(*xp,nzxopts);
  2067. #else
  2068. /* Here we're trying to fix a problem in which a directory name is accepted */
  2069. /* as a filename, but this breaks too many other things. */
  2070.         /* nzxopts = 0; */
  2071.         if (!d) {
  2072.             if (itsadir & !iswild(*xp)) {
  2073.             debug(F100,"cmifi dir when filonly","",0);
  2074.             printf("?Not a regular file: \"%s\"\n",*xp);
  2075.             if (sv) free(sv);
  2076.             if (np) free(np);
  2077.             return(-9);
  2078.             } else {
  2079.             nzxopts |= ZX_FILONLY;
  2080.             if (matchdot)  nzxopts |= ZX_MATCHDOT;
  2081.             if (recursive) nzxopts |= ZX_RECURSE;
  2082.             y = nzxpand(*xp,nzxopts);
  2083.             }
  2084.         }
  2085. #endif /* COMMENT */
  2086.         nfiles = y;
  2087.         debug(F111,"cmifi y nzxpand",*xp,y);
  2088.         debug(F111,"cmifi y atmbuf",atmbuf,itsadir);
  2089.         expanded = 1;
  2090.         }
  2091.         /* domydir() calls zxrewind() so we MUST call nzxpand() here */
  2092.         if (!expanded && diractive) {
  2093.         debug(F110,"cmifi diractive catch-all zxpand",*xp,0);
  2094.         nzxopts |= (d == 0) ? ZX_FILONLY : (dirflg ? ZX_DIRONLY : 0);
  2095.         if (matchdot)  nzxopts |= ZX_MATCHDOT;
  2096.         if (recursive) nzxopts |= ZX_RECURSE;
  2097.         y = nzxpand(*xp,nzxopts);
  2098.         debug(F111,"cmifi diractive nzxpand",*xp,y);
  2099.         nfiles = y;
  2100.         expanded = 1;
  2101.         }
  2102.         *wild = (iswild(sv) || (y > 1)) && (itsadir == 0);
  2103.  
  2104. #ifdef RECURSIVE
  2105.         if (!*wild) *wild = recursive;
  2106. #endif /* RECURSIVE */
  2107.  
  2108.         debug(F111,"cmifi sv wild",sv,*wild);
  2109.         debug(F101,"cmifi y","",y);
  2110.         if (dirflg && *wild && cdactive) {
  2111.         if (y > 1) {
  2112.             printf("?Wildcard matches more than one directory\n");
  2113.             if (sv) free(sv);
  2114.             if (np) free(np);
  2115.             return(-9);
  2116.         } else {
  2117.             znext(*xp);
  2118.         }
  2119.         }
  2120.         if (itsadir && d && !dirflg) { /* It's a directory and not wild */
  2121.         if (sv) free(sv);    /* and it's ok to parse directories */
  2122.         if (np) free(np);
  2123. #ifndef NOLASTFILE
  2124.         makestr(&lastfile,tmplastfile);
  2125. #endif    /* NOLASTFILE */
  2126.         return(x);
  2127.         }
  2128.         if (y == 0) {        /* File was not found */
  2129.         int dosearch = 0;
  2130.         dosearch = (path != NULL); /* A search path was given */
  2131.         if (dosearch) {
  2132.             dosearch = hasnopath(sv); /* Filename includes no path */
  2133.             debug(F111,"cmifip hasnopath",sv,dosearch);
  2134.         }
  2135.         if (dosearch) {        /* Search the path... */
  2136.             char * ptr = path;
  2137.             char c;
  2138.             while (1) {
  2139.             c = *ptr;
  2140.             if (c == PATHSEP || c == NUL) {
  2141.                 if (!*path) {
  2142.                 path = NULL;
  2143.                 break;
  2144.                 }
  2145.                 *ptr = NUL;
  2146. #ifdef UNIX
  2147. /* By definition of CDPATH, an empty member denotes the current directory */
  2148.                 if (!*path)
  2149.                   ckstrncpy(atmbuf,".",ATMBL);
  2150.                 else
  2151. #endif /* UNIX */
  2152.                   ckstrncpy(atmbuf,path,ATMBL);
  2153. #ifdef VMS
  2154.                 atmbuf[ATMBL] = NUL;
  2155. /* If we have a logical name, evaluate it recursively */
  2156.                 if (*(ptr-1) == ':') { /* Logical name ends in : */
  2157.                 char *p; int n;
  2158.                 while (((n = strlen(atmbuf))  > 0) &&
  2159.                        atmbuf[n-1] == ':') {
  2160.                     atmbuf[n-1] = NUL;
  2161.                     for (p = atmbuf; *p; p++)
  2162.                       if (islower(*p)) *p = toupper(*p);
  2163.                     debug(F111,"cmdir CDPATH LN 1",atmbuf,n);
  2164.                     p = getenv(atmbuf);
  2165.                     debug(F110,"cmdir CDPATH LN 2",p,0);
  2166.                     if (!p)
  2167.                       break;
  2168.                     strncpy(atmbuf,p,ATMBL);
  2169.                     atmbuf[ATMBL] = NUL;
  2170.                 }
  2171.                 }
  2172. #else
  2173. #ifdef OS2
  2174.                 if (*(ptr-1) != '\\' && *(ptr-1) != '/')
  2175.                   ckstrncat(atmbuf,"\\",ATMBL);
  2176. #else
  2177. #ifdef UNIX
  2178.                 if (*(ptr-1) != '/')
  2179.                   ckstrncat(atmbuf,"/",ATMBL);
  2180. #else
  2181. #ifdef datageneral
  2182.                 if (*(ptr-1) != ':')
  2183.                   ckstrncat(atmbuf,":",ATMBL);
  2184. #endif /* datageneral */
  2185. #endif /* UNIX */
  2186. #endif /* OS2 */
  2187. #endif /* VMS */
  2188.                 ckstrncat(atmbuf,sv,ATMBL);
  2189.                 debug(F110,"cmifip add path",atmbuf,0);
  2190.                 if (c == PATHSEP) ptr++;
  2191.                 path = ptr;
  2192.                 break;
  2193.             }
  2194.             ptr++;
  2195.             }
  2196.             x = 1;
  2197.             inword = 0;
  2198.             cc = 0;
  2199.             xc = (int) strlen(atmbuf);
  2200.             *xp = "";
  2201.             goto i_path;
  2202.         }
  2203.         if (d) {
  2204.             if (sv) free(sv);
  2205.             if (np) free(np);
  2206.             return(-2);
  2207.         } else {
  2208.             if (!nomsg) {
  2209. #ifdef CKROOT
  2210.             if (ckrooterr)
  2211.               printf("?Off Limits: %s\n",sv);
  2212.             else
  2213. #endif /* CKROOT */
  2214.               if (!quiet)
  2215.                 printf("?No %s match - %s\n",
  2216.                  dirflg ? "directories" : "files", sv);
  2217.             }
  2218.             if (sv) free(sv);
  2219.             if (np) free(np);
  2220.             return(-9);
  2221.         }
  2222.         } else if (y < 0) {
  2223. #ifdef CKROOT
  2224.         if (ckrooterr)
  2225.           printf("?Off Limits: %s\n",sv);
  2226.         else
  2227. #endif /* CKROOT */
  2228.           printf("?Too many %s match - %s\n",
  2229.              dirflg ? "directories" : "files", sv);
  2230.         if (sv) free(sv);
  2231.         if (np) free(np);
  2232.         return(-9);
  2233.         } else if (*wild || y > 1) {
  2234.         if (sv) free(sv);
  2235.         if (np) free(np);
  2236. #ifndef NOLASTFILE
  2237.         makestr(&lastfile,tmplastfile);
  2238. #endif    /* NOLASTFILE */
  2239.         return(x);
  2240.         }
  2241.  
  2242.         /* If not wild, see if it exists and is readable. */
  2243.  
  2244.         debug(F111,"cmifi sv not wild",sv,*wild);
  2245.         if (expanded)
  2246.           znext(*xp);        /* Get first (only?) matching file */
  2247.         if (dirflg)            /* Maybe wild and expanded */
  2248.           itsadir = isdir(*xp);    /* so do this again. */
  2249.         filesize = dirflg ? itsadir : zchki(*xp); /* Check accessibility */
  2250.         if (expanded) {
  2251. #ifdef ZXREWIND
  2252.         nfiles = zxrewind();    /* Rewind so next znext() gets 1st */
  2253. #else
  2254.  
  2255.         nzxopts |= dirflg ? ZX_DIRONLY : 0;
  2256.         if (matchdot)  nzxopts |= ZX_MATCHDOT;
  2257.         if (recursive) nzxopts |= ZX_RECURSE;
  2258.         nfiles = nzxpand(*xp,nzxopts);
  2259. #endif /* ZXREWIND */
  2260.         }
  2261.         debug(F111,"cmifi nfiles",*xp,nfiles);
  2262.         debug(F101,"cmifi filesize","",filesize);
  2263.         free(sv);            /* done with this */
  2264.         sv = NULL;
  2265.         if (dirflg && !filesize) {
  2266.         printf("?Not a directory - %s\n",*xp);
  2267. #ifdef CKCHANNELIO
  2268.         z_error = FX_ACC;
  2269. #endif /* CKCHANNELIO */
  2270.         return(-9);
  2271.         } else if (filesize == (CK_OFF_T)-3) {
  2272.         if (!xcmfdb) {
  2273.             if (diractive)
  2274.               /* Don't show filename if we're not allowed to see it */
  2275.               printf("?Read permission denied\n");
  2276.             else
  2277.               printf("?Read permission denied - %s\n",*xp);
  2278.         }
  2279.         if (np) free(np);
  2280. #ifdef CKCHANNELIO
  2281.         z_error = FX_ACC;
  2282. #endif /* CKCHANNELIO */
  2283.         return(xcmfdb ? -6 : -9);
  2284.         } else if (filesize == (CK_OFF_T)-2) {
  2285.         if (!recursive) {
  2286.             if (np) free(np);
  2287.             if (d) {
  2288. #ifndef NOLASTFILE
  2289.             makestr(&lastfile,tmplastfile);
  2290. #endif    /* NOLASTFILE */
  2291.             return(0);
  2292.             }
  2293.             if (!xcmfdb)
  2294.               printf("?File not readable - %s\n",*xp);
  2295. #ifdef CKCHANNELIO
  2296.             z_error = FX_ACC;
  2297. #endif /* CKCHANNELIO */
  2298.             return(xcmfdb ? -6 : -9);
  2299.         }
  2300.         } else if (filesize < (CK_OFF_T)0) {
  2301.         if (np) free(np);
  2302.         if (!nomsg && !xcmfdb)
  2303.           printf("?File not found - %s\n",*xp);
  2304. #ifdef CKCHANNELIO
  2305.         z_error = FX_FNF;
  2306. #endif /* CKCHANNELIO */
  2307.         return(xcmfdb ? -6 : -9);
  2308.         }
  2309.         if (np) free(np);
  2310. #ifndef NOLASTFILE
  2311.         makestr(&lastfile,tmplastfile);
  2312. #endif    /* NOLASTFILE */
  2313.         return(x);
  2314.  
  2315. #ifndef MAC
  2316.       case 2:            /* ESC */
  2317.         debug(F101,"cmifi esc, xc","",xc);
  2318.         if (xc == 0) {
  2319.         if (*xdef) {
  2320.             printf("%s ",xdef); /* If at beginning of field */
  2321. #ifdef GEMDOS
  2322.             fflush(stdout);
  2323. #endif /* GEMDOS */
  2324.             inword = cmflgs = 0;
  2325.             addbuf(xdef);    /* Supply default. */
  2326.             if (setatm(xdef,0) < 0) {
  2327.             printf("Default name too long\n");
  2328.             if (np) free(np);
  2329.             return(-9);
  2330.             }
  2331.         } else {        /* No default */
  2332.             bleep(BP_WARN);
  2333.         }
  2334.         break;
  2335.         }
  2336.         if (**xp == '{') {        /* Did user type opening brace... */
  2337.         *xp = *xp + 1;
  2338.         xc--;
  2339.         cc--;
  2340.         qflag = '}';
  2341.         } else if (dblquo && **xp == '"') {    /* or doublequote? */
  2342.         *xp = *xp + 1;        /* If so ignore it and space past it */
  2343.         xc--;
  2344.         cc--;
  2345.         qflag = '"';
  2346.         }
  2347. #ifndef NOSPL
  2348.         if (f) {            /* If a conversion function is given */
  2349. #ifdef DOCHKVAR
  2350.         char *s = *xp;        /* See if there are any variables in */
  2351.         while (*s) {        /* the string and if so, expand it.  */
  2352.             if (chkvar(s)) {
  2353. #endif /* DOCHKVAR */
  2354.             zq = atxbuf;
  2355.             atxn = CMDBL;
  2356.             if ((x = (*f)(*xp,&zq,&atxn)) < 0) {
  2357.                 if (np) free(np);
  2358.                 return(-2);
  2359.             }
  2360. #ifdef DOCHKVAR
  2361.             /* reduce cc by number of \\ consumed by conversion */
  2362.             /* function (needed for OS/2, where \ is path separator) */
  2363.             cc -= (strlen(*xp) - strlen(atxbuf));
  2364. #endif /* DOCHKVAR */
  2365.             *xp = atxbuf;
  2366.             if (!atxbuf[0]) { /* Result empty, use default */
  2367.                 *xp = xdef;
  2368.                 cc = strlen(xdef);
  2369.             }
  2370. #ifdef DOCHKVAR
  2371.             break;
  2372.             }
  2373.             s++;
  2374.         }
  2375. #endif /* DOCHKVAR */
  2376.         }
  2377. #endif /* NOSPL */
  2378.  
  2379. #ifdef DTILDE
  2380.         if (dirflg && *(*xp) == '~') {
  2381.         debug(F111,"cmifi tilde_expand A",*xp,cc);
  2382.         dirp = tilde_expand(*xp); /* Expand tilde, if any... */
  2383.         if (!dirp) dirp = "";
  2384.         if (*dirp) {
  2385.             int i, xx;
  2386.             char * sp;
  2387.             xc = cc;        /* Length of ~thing */
  2388.             xx = setatm(dirp,0); /* Copy expansion to atom buffer */
  2389.             debug(F111,"cmifi tilde_expand B",atmbuf,cc);
  2390.             if (xx < 0) {
  2391.             printf("Expanded name too long\n");
  2392.             if (np) free(np);
  2393.             return(-9);
  2394.             }
  2395.             debug(F111,"cmifi tilde_expand xc","",xc);
  2396.             for (i = 0; i < xc; i++) {
  2397.             cmdchardel();    /* Back up over ~thing */
  2398.             bp--;
  2399.             }
  2400.             xc = cc;        /* How many new ones we just got */
  2401.             sp = atmbuf;
  2402.             printf("%s",sp);    /* Print them */
  2403.             while ((*bp++ = *sp++)) ;    /* Copy to command buffer */
  2404.             bp--;                    /* Back up over NUL */
  2405.         }
  2406.         *xp = atmbuf;
  2407.         }
  2408. #endif /* DTILDE */
  2409.  
  2410.         sp = *xp + cc;
  2411.  
  2412. #ifdef UNIXOROSK
  2413.         if (!strcmp(atmbuf,"..")) {
  2414.         printf(" ");
  2415.         ckstrncat(cmdbuf," ",CMDBL);
  2416.         cc++;
  2417.         bp++;
  2418.         *wild = 0;
  2419.         *xp = atmbuf;
  2420.         break;
  2421.         } else if (!strcmp(atmbuf,".")) {
  2422.         bleep(BP_WARN);
  2423.         if (np) free(np);
  2424.         return(-1);
  2425.         } else {
  2426.         /* This patches a glitch when user types "./foo<ESC>" */
  2427.         /* in which the next two chars are omitted from the */
  2428.         /* expansion.  There should be a better fix, however, */
  2429.         /* since there is no problem with "../foo<ESC>". */
  2430.         char *p = *xp;
  2431.         if (*p == '.' && *(p+1) == '/')
  2432.           cc -= 2;
  2433.         }
  2434. #endif /* UNIXOROSK */
  2435.  
  2436. #ifdef datageneral
  2437.         *sp++ = '+';        /* Data General AOS wildcard */
  2438. #else
  2439.         *sp++ = '*';        /* Others */
  2440. #endif /* datageneral */
  2441.         *sp-- = '\0';
  2442. #ifdef GEMDOS
  2443.         if (!strchr(*xp, '.'))    /* abde.e -> abcde.e* */
  2444.           strcat(*xp, ".*");    /* abc -> abc*.* */
  2445. #endif /* GEMDOS */
  2446.         /* Add wildcard and expand list. */
  2447. #ifdef COMMENT
  2448.         /* This kills partial completion when ESC given in path segment */
  2449.         nzxopts |= dirflg ? ZX_DIRONLY : (d ? 0 : ZX_FILONLY);
  2450. #else
  2451.         /* nzxopts = 0; */
  2452. #endif /* COMMENT */
  2453.         if (matchdot)  nzxopts |= ZX_MATCHDOT;
  2454.         if (recursive) nzxopts |= ZX_RECURSE;
  2455.         y = nzxpand(*xp,nzxopts);
  2456.         nfiles = y;
  2457.         debug(F111,"cmifi nzxpand",*xp,y);
  2458.         if (y > 0) {
  2459. #ifdef OS2
  2460.                 znext(filbuf);        /* Get first */
  2461. #ifdef ZXREWIND
  2462.         zxrewind();        /* Must "rewind" */
  2463. #else
  2464.         nzxpand(*xp,nxzopts);
  2465. #endif /* ZXREWIND */
  2466. #else  /* Not OS2 */
  2467.                 ckstrncpy(filbuf,mtchs[0],CKMAXPATH);
  2468. #endif /* OS2 */
  2469.         } else
  2470.           *filbuf = '\0';
  2471.         filbuf[CKMAXPATH] = NUL;
  2472.         *sp = '\0';            /* Remove wildcard. */
  2473.         debug(F111,"cmifi filbuf",filbuf,y);
  2474.         debug(F111,"cmifi *xp",*xp,cc);
  2475.  
  2476.         *wild = (y > 1);
  2477.         if (y == 0) {
  2478.         if (!nomsg) {
  2479. #ifdef CKROOT
  2480.             if (ckrooterr)
  2481.               printf("?Off Limits: %s\n",atmbuf);
  2482.             else
  2483. #endif /* CKROOT */
  2484.               printf("?No %s match - %s\n",
  2485.                dirflg ? "directories" : "files", atmbuf);
  2486.             if (np) free(np);
  2487.             return(-9);
  2488.         } else {
  2489.             bleep(BP_WARN);
  2490.             if (np) free(np);
  2491.             return(-1);
  2492.         }
  2493.         } else if (y < 0) {
  2494. #ifdef CKROOT
  2495.         if (ckrooterr)
  2496.           printf("?Off Limits: %s\n",atmbuf);
  2497.         else
  2498. #endif /* CKROOT */
  2499.           printf("?Too many %s match - %s\n",
  2500.              dirflg ? "directories" : "files", atmbuf);
  2501.         if (np) free(np);
  2502.         return(-9);
  2503.         } else if (y > 1        /* Not unique */
  2504. #ifndef VMS
  2505.                || (y == 1 && isdir(filbuf)) /* Unique directory */
  2506. #endif /* VMS */
  2507.                ) {
  2508. #ifndef NOPARTIAL
  2509. /* Partial filename completion */
  2510.         int j, k; char c;
  2511.         k = 0;
  2512.         debug(F111,"cmifi partial",filbuf,cc);
  2513. #ifdef OS2
  2514.         {
  2515.             int cur = 0,
  2516.             len = 0,
  2517.             len2 = 0,
  2518.             min = strlen(filbuf),
  2519.             found = 0;
  2520.             char localfn[CKMAXPATH+1];
  2521.  
  2522.             len = min;
  2523.             for (j = 1; j <= y; j++) {
  2524.             znext(localfn);
  2525.             if (dirflg && !isdir(localfn))
  2526.               continue;
  2527.             found = 1;
  2528.             len2 = strlen(localfn);
  2529.             for (cur = cc;
  2530.                  cur < len && cur < len2 && cur <= min;
  2531.                  cur++
  2532.                  ) {
  2533.                             /* OS/2 or Windows, case doesn't matter */
  2534.                 if (tolower(filbuf[cur]) != tolower(localfn[cur]))
  2535.                   break;
  2536.             }
  2537.             if (cur < min)
  2538.               min = cur;
  2539.             }
  2540.             if (!found)
  2541.               min = cc;
  2542.             filbuf[min] = NUL;
  2543.             if (min > cc)
  2544.               k++;
  2545.         }
  2546. #else /* OS2 */
  2547.         for (i = cc; (c = filbuf[i]); i++) {
  2548.             for (j = 1; j < y; j++)
  2549.               if (mtchs[j][i] != c) break;
  2550.             if (j == y) k++;
  2551.             else filbuf[i] = filbuf[i+1] = NUL;
  2552.         }
  2553. #endif /* OS2 */
  2554.  
  2555.  
  2556. #ifndef VMS
  2557.         /* isdir() function required for this! */
  2558.         if (y == 1 && isdir(filbuf)) { /* Dont we already know this? */
  2559.             int len;
  2560.             len = strlen(filbuf);
  2561.             if (len > 0 && len < ATMBL - 1) {
  2562.             if (filbuf[len-1] != dirsep) {
  2563.                 filbuf[len] = dirsep;
  2564.                 filbuf[len+1] = NUL;
  2565.             }
  2566.             }
  2567. /*
  2568.   At this point, before just doing partial completion, we should look first to
  2569.   see if the given directory does indeed have any subdirectories (dirflg) or
  2570.   files (!dirflg); if it doesn't we should do full completion.  Otherwise, the
  2571.   result looks funny to the user and "?" blows up the command for no good
  2572.   reason.
  2573. */
  2574.             {
  2575.             int flags = 0;
  2576.             filbuf[len+1] = '*';
  2577.             filbuf[len+2] = NUL;
  2578.             if (dirflg) flags = ZX_DIRONLY;
  2579.             children = nzxpand(filbuf,flags);
  2580.             debug(F111,"cmifi children",filbuf,children);
  2581.             filbuf[len+1] = NUL;
  2582.             nzxpand(filbuf,flags); /* Restore previous list */
  2583.             if (children == 0)
  2584.               goto NOSUBDIRS;
  2585.             }
  2586.             if (len + 1 > cc)
  2587.               k++;
  2588.         }
  2589.                 /* Add doublequotes if there are spaces in the name */
  2590.         {
  2591.             int x;
  2592.             if (qflag) {
  2593.             x = (qflag == '}'); /* (or braces) */
  2594.             } else {
  2595.             x = !dblquo;
  2596.             }
  2597.             if (filbuf[0] != '"' && filbuf[0] != '{')
  2598.               k = dquote(filbuf,ATMBL,x);
  2599.         }
  2600. #endif /* VMS */
  2601.         debug(F111,"cmifi REPAINT filbuf",filbuf,k);
  2602.         if (k > 0) {        /* Got more characters */
  2603.             debug(F101,"cmifi REPAINT cc","",cc);
  2604.             debug(F101,"cmifi REPAINT xc","",xc);
  2605.             debug(F110,"cmifi REPAINT bp-cc",bp-cc,0);
  2606.             debug(F110,"cmifi REPAINT bp-xc",bp-xc,0);
  2607.             sp = filbuf + cc;    /* Point to new ones */
  2608.             if (qflag || strncmp(filbuf,bp-cc,cc)) { /* Repaint? */
  2609.             int x;
  2610.             x = cc;
  2611.             if (qflag) x++;
  2612.             for (i = 0; i < x; i++) {
  2613.                 cmdchardel(); /* Back up over old partial spec */
  2614.                 bp--;
  2615.             }
  2616.             sp = filbuf;    /* Point to new word start */
  2617.             debug(F110,"cmifi erase ok",sp,0);
  2618.             }
  2619.             cc = k;        /* How many new ones we just got */
  2620.             printf("%s",sp);    /* Print them */
  2621.             while ((*bp++ = *sp++)) ;    /* Copy to command buffer */
  2622.             bp--;                    /* Back up over NUL */
  2623.             debug(F110,"cmifi partial cmdbuf",cmdbuf,0);
  2624.             if (setatm(filbuf,0) < 0) {
  2625.             printf("?Partial name too long\n");
  2626.             if (np) free(np);
  2627.             return(-9);
  2628.             }
  2629.             debug(F111,"cmifi partial atmbuf",atmbuf,cc);
  2630.             *xp = atmbuf;
  2631.         }
  2632. #endif /* NOPARTIAL */
  2633.         bleep(BP_WARN);
  2634.         } else {            /* Unique, complete it.  */
  2635. #ifndef VMS
  2636. #ifdef CK_TMPDIR
  2637.         /* isdir() function required for this! */
  2638.           NOSUBDIRS:
  2639.         debug(F111,"cmifi unique",filbuf,children);
  2640.         if (isdir(filbuf) && children > 0) {
  2641.             int len;
  2642.             len = strlen(filbuf);
  2643.             if (len > 0 && len < ATMBL - 1) {
  2644.             if (filbuf[len-1] != dirsep) {
  2645.                 filbuf[len] = dirsep;
  2646.                 filbuf[len+1] = NUL;
  2647.             }
  2648.             }
  2649.             sp = filbuf + cc;
  2650.             bleep(BP_WARN);
  2651.             printf("%s",sp);
  2652.             cc++;
  2653.             while ((*bp++ = *sp++)) ;
  2654.             bp--;
  2655.             if (setatm(filbuf,0) < 0) {
  2656.             printf("?Directory name too long\n");
  2657.             if (np) free(np);
  2658.             return(-9);
  2659.             }
  2660.             debug(F111,"cmifi directory atmbuf",atmbuf,cc);
  2661.             *xp = atmbuf;
  2662.         } else {        /* Not a directory or dirflg */
  2663. #endif /* CK_TMPDIR */
  2664. #endif /* VMS */
  2665. #ifndef VMS                /* VMS dir names are special */
  2666. #ifndef datageneral            /* VS dirnames must not end in ":" */
  2667.             if (dirflg) {
  2668.             int len;
  2669.             len = strlen(filbuf);
  2670.             if (len > 0 && len < ATMBL - 1) {
  2671.                 if (filbuf[len-1] != dirsep) {
  2672.                 filbuf[len] = dirsep;
  2673.                 filbuf[len+1] = NUL;
  2674.                 }
  2675.             }
  2676.             }
  2677. #endif /* datageneral */
  2678. #endif /* VMS */
  2679.             sp = filbuf + cc;    /* Point past what user typed. */
  2680.             {
  2681.             int x;
  2682.             if (qflag) {
  2683.                 x = (qflag == '}');
  2684.             } else {
  2685.                 x = !dblquo;
  2686.             }
  2687.             if (filbuf[0] != '"' && filbuf[0] != '{')
  2688.               dquote(filbuf,ATMBL,x);
  2689.             }
  2690.             if (qflag || strncmp(filbuf,bp-cc,cc)) { /* Repaint? */
  2691.             int x;
  2692.             x = cc;
  2693.             if (qflag) x++;
  2694.             for (i = 0; i < x; i++) {
  2695.                 cmdchardel(); /* Back up over old partial spec */
  2696.                 bp--;
  2697.             }
  2698.             sp = filbuf;    /* Point to new word start */
  2699.             debug(F111,"cmifi after erase sp=",sp,cc);
  2700.             }
  2701.             printf("%s ",sp);    /* Print the completed name. */
  2702. #ifdef GEMDOS
  2703.             fflush(stdout);
  2704. #endif /* GEMDOS */
  2705.             addbuf(sp);        /* Add the characters to cmdbuf. */
  2706.             if (setatm(filbuf,0) < 0) { /* And to atmbuf. */
  2707.             printf("?Completed name too long\n");
  2708.             if (np) free(np);
  2709.             return(-9);
  2710.             }
  2711.             inword = cmflgs = 0;
  2712.             *xp = brstrip(atmbuf); /* Return pointer to atmbuf. */
  2713.             if (dirflg && !isdir(*xp)) {
  2714.             printf("?Not a directory - %s\n", filbuf);
  2715.             if (np) free(np);
  2716.             return(-9);
  2717.             }
  2718.             if (np) free(np);
  2719. #ifndef NOLASTFILE
  2720.             makestr(&lastfile,tmplastfile);
  2721. #endif    /* NOLASTFILE */
  2722.             return(0);
  2723. #ifndef VMS
  2724. #ifdef CK_TMPDIR
  2725.         }
  2726. #endif /* CK_TMPDIR */
  2727. #endif /* VMS */
  2728.         }
  2729.         break;
  2730.  
  2731.       case 3:            /* Question mark - file menu wanted */
  2732.         if (*xhlp == NUL)
  2733.           printf(dirflg ? " Directory name" : " Input file specification");
  2734.         else
  2735.           printf(" %s",xhlp);
  2736. #ifdef GEMDOS
  2737.         fflush(stdout);
  2738. #endif /* GEMDOS */
  2739.         /* If user typed an opening quote or brace, just skip past it */
  2740.  
  2741.         if (**xp == '"' || **xp == '{') {
  2742.         *xp = *xp + 1;
  2743.         xc--;
  2744.         cc--;
  2745.         }
  2746. #ifndef NOSPL
  2747.         if (f) {            /* If a conversion function is given */
  2748. #ifdef DOCHKVAR
  2749.         char *s = *xp;        /* See if there are any variables in */
  2750.         while (*s) {        /* the string and if so, expand them */
  2751.             if (chkvar(s)) {
  2752. #endif /* DOCHKVAR */
  2753.             zq = atxbuf;
  2754.             atxn = CMDBL;
  2755.             if ((x = (*f)(*xp,&zq,&atxn)) < 0) {
  2756.                 if (np) free(np);
  2757.                 return(-2);
  2758.             }
  2759. #ifdef DOCHKVAR
  2760.             /* reduce cc by number of \\ consumed by conversion */
  2761.             /* function (needed for OS/2, where \ is path separator) */
  2762.             cc -= (strlen(*xp) - strlen(atxbuf));
  2763. #endif /* DOCHKVAR */
  2764.             *xp = atxbuf;
  2765. #ifdef DOCHKVAR
  2766.             break;
  2767.             }
  2768.             s++;
  2769.         }
  2770. #endif /* DOCHKVAR */
  2771.         }
  2772. #endif /* NOSPL */
  2773.         debug(F111,"cmifi ? *xp, cc",*xp,cc);
  2774.         sp = *xp + cc;        /* Insert "*" at end */
  2775. #ifdef datageneral
  2776.         *sp++ = '+';        /* Insert +, the DG wild card */
  2777. #else
  2778.         *sp++ = '*';
  2779. #endif /* datageneral */
  2780.         *sp-- = '\0';
  2781. #ifdef GEMDOS
  2782.         if (! strchr(*xp, '.'))    /* abde.e -> abcde.e* */
  2783.           strcat(*xp, ".*");    /* abc -> abc*.* */
  2784. #endif /* GEMDOS */
  2785.         debug(F110,"cmifi ? wild",*xp,0);
  2786.  
  2787.         nzxopts |= dirflg ? ZX_DIRONLY : (d ? 0 : ZX_FILONLY);
  2788.  
  2789.         debug(F101,"cmifi matchdot","",matchdot);
  2790.         if (matchdot)  nzxopts |= ZX_MATCHDOT;
  2791.         if (recursive) nzxopts |= ZX_RECURSE;
  2792.         y = nzxpand(*xp,nzxopts);
  2793.         nfiles = y;
  2794.         *sp = '\0';
  2795.         if (y == 0) {
  2796.         if (nomsg) {
  2797.             printf(": %s\n",atmbuf);
  2798.             printf("%s%s",cmprom,cmdbuf);
  2799.             fflush(stdout);
  2800.             if (np) free(np);
  2801.             return(-1);
  2802.         } else {
  2803. #ifdef CKROOT
  2804.             if (ckrooterr)
  2805.               printf("?Off Limits: %s\n",atmbuf);
  2806.             else
  2807. #endif /* CKROOT */
  2808.               printf("?No %s match - %s\n",
  2809.                  dirflg ? "directories" : "files", atmbuf);
  2810.             if (np) free(np);
  2811.             return(-9);
  2812.         }
  2813.         } else if (y < 0) {
  2814. #ifdef CKROOT
  2815.         if (ckrooterr)
  2816.           printf("?Off Limits: %s\n",atmbuf);
  2817.         else
  2818. #endif /* CKROOT */
  2819.           printf("?Too many %s match - %s\n",
  2820.              dirflg ? "directories" : "files", atmbuf);
  2821.         if (np) free(np);
  2822.         return(-9);
  2823.         } else {
  2824.         printf(", one of the following:\n");
  2825.         if (filhelp((int)y,"","",1,dirflg) < 0) {
  2826.             if (np) free(np);
  2827.             return(-9);
  2828.         }
  2829.         }
  2830.         printf("%s%s",cmprom,cmdbuf);
  2831.         fflush(stdout);
  2832.         break;
  2833. #endif /* MAC */
  2834.     }
  2835. #ifdef BS_DIRSEP
  2836.         dirnamflg = 1;
  2837.         x = gtword(0);                  /* No, get a word */
  2838.     dirnamflg = 0;
  2839. #else
  2840.         x = gtword(0);                  /* No, get a word */
  2841. #endif /* BS_DIRSEP */
  2842.     *xp = atmbuf;
  2843.     }
  2844. }
  2845.  
  2846. /*  C M F L D  --  Parse an arbitrary field  */
  2847. /*
  2848.   Returns:
  2849.     -3 if no input present when required,
  2850.     -2 if field too big for buffer,
  2851.     -1 if reparse needed,
  2852.      0 otherwise, xp pointing to string result.
  2853.  
  2854.   NOTE: Global flag keepallchars says whether this routine should break on CR
  2855.   or LF: needed for MINPUT targets and DECLARE initializers, where we want to
  2856.   keep control characters if the user specifies them (March 2003).  It might
  2857.   have been better to change the calling sequence but that was not practical.
  2858. */
  2859. int
  2860. cmfld(xhlp,xdef,xp,f) char *xhlp, *xdef, **xp; xx_strp f; {
  2861.     int x, xc;
  2862.     char *zq;
  2863.  
  2864.     inword = 0;                /* Initialize counts & pointers */
  2865.     cc = 0;
  2866.     xc = 0;
  2867.     *xp = "";
  2868.  
  2869.     debug(F110,"cmfld xdef 1",xdef,0);
  2870.  
  2871.     if (!xhlp) xhlp = "";
  2872.     if (!xdef) xdef = "";
  2873.     ckstrncpy(cmdefault,xdef,CMDEFAULT); /* Copy default */
  2874.     xdef = cmdefault;
  2875.  
  2876.     debug(F111,"cmfld xdef 2",xdef,cmflgs);
  2877.     debug(F111,"cmfld atmbuf 1",atmbuf,xc);
  2878.  
  2879.     if ((x = cmflgs) != 1) {            /* Already confirmed? */
  2880.         x = gtword(0);                  /* No, get a word */
  2881.     } else {
  2882.     if (setatm(xdef,0) < 0) {    /* If so, use default, if any. */
  2883.         printf("?Default too long\n");
  2884.         return(-9);
  2885.     }
  2886.     }
  2887.     *xp = atmbuf;                       /* Point to result. */
  2888.     debug(F111,"cmfld atmbuf 2",atmbuf,cmflgs);
  2889.  
  2890.     while (1) {
  2891.         xc += cc;                       /* Count the characters. */
  2892.         debug(F111,"cmfld gtword",atmbuf,xc);
  2893.         debug(F101,"cmfld x","",x);
  2894.         switch (x) {
  2895.       case -9:
  2896.         printf("Command or field too long\n");
  2897.       case -4:            /* EOF */
  2898.       case -3:            /* Empty. */
  2899.       case -2:            /* Out of space. */
  2900.       case -1:            /* Reparse needed */
  2901.         return(x);
  2902.       case 1:            /* CR */
  2903.       case 0:            /* SP */
  2904.         debug(F111,"cmfld 1",atmbuf,xc);
  2905.         if (xc == 0) {        /* If no input, return default. */
  2906.         if (setatm(xdef,0) < 0) {
  2907.             printf("?Default too long\n");
  2908.             return(-9);
  2909.         }
  2910.         }
  2911.         *xp = atmbuf;        /* Point to what we got. */
  2912.         debug(F111,"cmfld 2",atmbuf,((f) ? 1 : 0));
  2913.         if (f) {            /* If a conversion function is given */
  2914.         zq = atxbuf;        /* employ it now. */
  2915.         atxn = CMDBL;
  2916.         if ((*f)(*xp,&zq,&atxn) < 0)
  2917.           return(-2);
  2918.         debug(F111,"cmfld 3",atxbuf,xc);
  2919.         /* Replace by new value -- for MINPUT only keep all chars */
  2920.         if (setatm(atxbuf,keepallchars ? 3:1) < 0) { /* 16 Mar 2003 */
  2921.             printf("Value too long\n");
  2922.             return(-9);
  2923.         }
  2924.         *xp = atmbuf;
  2925.         }
  2926.         debug(F111,"cmfld 4",atmbuf,xc);
  2927.         if (**xp == NUL) {        /* If variable evaluates to null */
  2928.         if (setatm(xdef,0) < 0) {
  2929.             printf("?Default too long\n");
  2930.             return(-9);
  2931.         }
  2932.         if (**xp == NUL) x = -3; /* If still empty, return -3. */
  2933.         }
  2934.         debug(F111,"cmfld returns",*xp,x);
  2935.         return(x);
  2936.       case 2:            /* ESC */
  2937.         if (xc == 0 && *xdef) {
  2938.         printf("%s ",xdef); /* If at beginning of field, */
  2939. #ifdef GEMDOS
  2940.         fflush(stdout);
  2941. #endif /* GEMDOS */
  2942.         addbuf(xdef);        /* Supply default. */
  2943.         inword = cmflgs = 0;
  2944.         if (setatm(xdef,0) < 0) {
  2945.             printf("?Default too long\n");
  2946.             return(-9);
  2947.         } else            /* Return as if whole field */
  2948.           return(0);        /* typed, followed by space. */
  2949.         } else {
  2950.         bleep(BP_WARN);
  2951.         }
  2952.         break;
  2953.       case 3:            /* Question mark */
  2954.         debug(F110,"cmfld QUESTIONMARK",cmdbuf,0);
  2955.         if (*xhlp == NUL)
  2956.           printf(" Please complete this field");
  2957.         else
  2958.           printf(" %s",xhlp);
  2959.         printf("\n%s%s",cmprom,cmdbuf);
  2960.         fflush(stdout);
  2961.         break;
  2962.         }
  2963.     debug(F111,"cmfld gtword A x",cmdbuf,x);
  2964.     x = gtword(0);
  2965.     debug(F111,"cmfld gtword B x",cmdbuf,x);
  2966.     }
  2967. }
  2968.  
  2969.  
  2970. /*  C M T X T  --  Get a text string, including confirmation  */
  2971.  
  2972. /*
  2973.   Print help message 'xhlp' if ? typed, supply default 'xdef' if null
  2974.   string typed.  Returns:
  2975.  
  2976.    -1 if reparse needed or buffer overflows.
  2977.     1 otherwise.
  2978.  
  2979.   with cmflgs set to return code, and xp pointing to result string.
  2980. */
  2981. int
  2982. cmtxt(xhlp,xdef,xp,f) char *xhlp; char *xdef; char **xp; xx_strp f; {
  2983.  
  2984.     int x, i;
  2985.     char *xx, *zq;
  2986.     static int xc;
  2987.  
  2988.     if (!xhlp) xhlp = "";
  2989.     if (!xdef) xdef = "";
  2990.  
  2991.     cmfldflgs = 0;
  2992.  
  2993.     cmdefault[0] = NUL;
  2994.     if (*xdef)
  2995.       ckstrncpy(cmdefault,xdef,CMDEFAULT); /* Copy default */
  2996.     xdef = cmdefault;
  2997.  
  2998.     debug(F101,"cmtxt cmflgs","",cmflgs);
  2999.     inword = 0;                /* Start atmbuf counter off at 0 */
  3000.     cc = 0;
  3001.     if (cmflgs == -1) {                 /* If reparsing, */
  3002.     *xp = pp;
  3003.         xc = (int)strlen(*xp);        /* get back the total text length, */
  3004.     bp = *xp;            /* and back up the pointers. */
  3005.     np = *xp;
  3006.     pp = *xp;
  3007.     } else {                            /* otherwise, */
  3008.     /* debug(F100,"cmtxt: fresh start","",0); */
  3009.         *xp = "";                       /* start fresh. */
  3010.         xc = 0;
  3011.     }
  3012.     *atmbuf = NUL;                      /* And empty the atom buffer. */
  3013.     rtimer();                /* Reset timer */
  3014.     if ((x = cmflgs) != 1) {
  3015.     int done = 0;
  3016.     while (!done) {
  3017.         x = gtword(0);        /* Get first word. */
  3018.         *xp = pp;            /* Save pointer to it. */
  3019.         /* debug(F111,"cmtxt:",*xp,cc); */
  3020.         if (x == -10) {
  3021.         if (gtimer() > timelimit) {
  3022.             /* if (!quiet) printf("?Timed out\n"); */
  3023.             return(x);
  3024.         }
  3025.         } else
  3026.           done = 1;
  3027.     }
  3028.     }
  3029.     while (1) {                /* Loop for each word in text. */
  3030.         xc += cc;                       /* Char count for all words. */
  3031.         /* debug(F111,"cmtxt gtword",atmbuf,xc); */
  3032.         /* debug(F101,"cmtxt x","",x); */
  3033.         switch (x) {
  3034.       case -10:
  3035.         if (gtimer() > timelimit) {
  3036. #ifdef IKSD
  3037.                 extern int inserver;
  3038.                 if (inserver) {
  3039.                     printf("\r\nIKSD IDLE TIMEOUT: %d sec\r\n", timelimit);
  3040.                     doexit(GOOD_EXIT,0);
  3041.                 }
  3042. #endif /* IKSD */
  3043.         /* if (!quiet) printf("?Timed out\n"); */
  3044.         return(-10);
  3045.         } else {
  3046.         x = gtword(0);
  3047.         continue;
  3048.         }
  3049.       case -9:            /* Buffer overflow */
  3050.         printf("Command or field too long\n");
  3051.       case -4:            /* EOF */
  3052. #ifdef MAC
  3053.       case -3:            /* Quit/Timeout */
  3054. #endif /* MAC */
  3055.       case -2:            /* Overflow */
  3056.       case -1:            /* Deletion */
  3057.         return(x);
  3058.       case 0:            /* Space */
  3059.         xc++;            /* Just count it */
  3060.         break;
  3061.       case 1:            /* CR or LF */
  3062.         if (xc == 0) *xp = xdef;
  3063.         if (f) {            /* If a conversion function is given */
  3064.         char * sx = atxbuf;
  3065.         zq = atxbuf;        /* Point to the expansion buffer */
  3066.         atxn = CMDBL;        /* specify its length */
  3067.         /* debug(F111,"cmtxt calling (*f)",*xp,atxbuf); */
  3068.         if ((x = (*f)(*xp,&zq,&atxn)) < 0) return(-2);
  3069.         sx = atxbuf;
  3070. #ifndef COMMENT
  3071.         cc = 0;
  3072.         while (*sx++) cc++;    /* (faster than calling strlen) */
  3073. #else
  3074.         cc = (int)strlen(atxbuf);
  3075. #endif /* COMMENT */
  3076.         /* Should be equal to (CMDBL - atxn) but isn't always. */
  3077.         /* Why not? */
  3078.         if (cc < 1) {        /* Nothing in expansion buffer? */
  3079.             *xp = xdef;        /* Point to default string instead. */
  3080. #ifndef COMMENT
  3081.             sx = xdef;
  3082.             while (*sx++) cc++;    /* (faster than calling strlen) */
  3083. #else
  3084.             cc = strlen(xdef);
  3085. #endif /* COMMENT */
  3086.         } else {        /* Expansion function got something */
  3087.             *xp = atxbuf;    /* return pointer to it. */
  3088.         }
  3089.         debug(F111,"cmtxt (*f)",*xp,cc);
  3090.         } else {            /* No expansion function */
  3091. #ifndef COMMENT
  3092.         /* Avoid a strlen() call */
  3093.         xx = *xp;
  3094.         cc = 0;
  3095.         while (*xx++) cc++;
  3096. #else
  3097.         /* NO!  xc is apparently not always set appropriately */
  3098.         cc = xc;
  3099. #endif /* COMMENT */
  3100.         }
  3101.         xx = *xp;
  3102. #ifdef COMMENT
  3103.         /* strlen() no longer needed */
  3104.         for (i = (int)strlen(xx) - 1; i > 0; i--)
  3105. #else
  3106.         for (i = cc - 1; i > 0; i--)
  3107. #endif /* COMMENT */
  3108.           if (xx[i] != SP)        /* Trim trailing blanks */
  3109.         break;
  3110.           else
  3111.         xx[i] = NUL;
  3112.         return(x);
  3113.       case 2:            /* ESC */
  3114.         if (xc == 0) {        /* Nothing typed yet */
  3115.         if (*xdef) {        /* Have a default for this field? */
  3116.             printf("%s ",xdef);    /* Yes, supply it */
  3117.             inword = cmflgs = 0;
  3118. #ifdef GEMDOS
  3119.             fflush(stdout);
  3120. #endif /* GEMDOS */
  3121.             cc = addbuf(xdef);
  3122.         } else bleep(BP_WARN);    /* No default */
  3123.         } else {            /* Already in field */
  3124.         int x; char *p;
  3125.         x = strlen(atmbuf);
  3126.         if (ckstrcmp(atmbuf,xdef,x,0)) {    /* Matches default? */
  3127.             bleep(BP_WARN);                /* No */
  3128.         } else if ((int)strlen(xdef) > x) { /* Yes */
  3129.             p = xdef + x;
  3130.             printf("%s ", p);
  3131. #ifdef GEMDOS
  3132.             fflush(stdout);
  3133. #endif /* GEMDOS */
  3134.             addbuf(p);
  3135.             inword = cmflgs = 0;
  3136.             debug(F110,"cmtxt: addbuf",cmdbuf,0);
  3137.         } else {
  3138.             bleep(BP_WARN);
  3139.         }
  3140.         }
  3141.         break;
  3142.       case 3:            /* Question Mark */
  3143.         if (*xhlp == NUL)
  3144.           printf(" Text string");
  3145.         else
  3146.           printf(" %s",xhlp);
  3147.         printf("\n%s%s",cmprom,cmdbuf);
  3148.         fflush(stdout);
  3149.         break;
  3150.       default:
  3151.         printf("?Unexpected return code from gtword() - %d\n",x);
  3152.         return(-2);
  3153.         }
  3154.         x = gtword(0);
  3155.     }
  3156. }
  3157.  
  3158. /*  C M K E Y  --  Parse a keyword  */
  3159.  
  3160. /*
  3161.  Call with:
  3162.    table    --  keyword table, in 'struct keytab' format;
  3163.    n        --  number of entries in table;
  3164.    xhlp     --  pointer to help string;
  3165.    xdef     --  pointer to default keyword;
  3166.    f        --  string preprocessing function (e.g. to evaluate variables)
  3167.    pmsg     --  0 = don't print error messages
  3168.                 1 = print error messages
  3169.                 2 = include CM_HLP keywords even if invisible
  3170.                 3 = 1+2
  3171.                 4 = parse a switch (keyword possibly ending in : or =)
  3172.                 8 = don't strip comments (used, e.g., for "help #")
  3173.  Returns:
  3174.    -3       --  no input supplied and no default available
  3175.    -2       --  input doesn't uniquely match a keyword in the table
  3176.    -1       --  user deleted too much, command reparse required
  3177.     n >= 0  --  value associated with keyword
  3178. */
  3179.  
  3180. /*
  3181.   Front ends for cmkey2(): 
  3182.   cmkey()  - The normal keyword parser
  3183.   cmkeyx() - Like cmkey() but suppresses error messages
  3184.   cmswi()  - Switch parser
  3185. */
  3186. int
  3187. cmkey(table,n,xhlp,xdef,f)
  3188. /* cmkey */  struct keytab table[]; int n; char *xhlp, *xdef; xx_strp f; {
  3189.     return(cmkey2(table,n,xhlp,xdef,"",f,1));
  3190. }
  3191. int
  3192. cmkeyx(table,n,xhlp,xdef,f)
  3193. /* cmkeyx */  struct keytab table[]; int n; char *xhlp, *xdef; xx_strp f; {
  3194.     return(cmkey2(table,n,xhlp,xdef,"",f,0));
  3195. }
  3196. int
  3197. cmswi(table,n,xhlp,xdef,f)
  3198. /* cmswi */  struct keytab table[]; int n; char *xhlp, *xdef; xx_strp f; {
  3199.     return(cmkey2(table,n,xhlp,xdef,"",f,4));
  3200. }
  3201.  
  3202. int
  3203. cmkey2(table,n,xhlp,xdef,tok,f,pmsg)
  3204.     struct keytab table[];
  3205.     int n;
  3206.     char *xhlp, *xdef;
  3207.     char *tok;
  3208.     xx_strp f;
  3209.     int pmsg;
  3210. { /* cmkey2 */
  3211.     extern int havetoken;
  3212.     int i, tl, y, z = 0, zz, xc, wordlen = 0, cmswitch;
  3213.     char *xp, *zq;
  3214.  
  3215.     if (!xhlp) xhlp = "";
  3216.     if (!xdef) xdef = "";
  3217.  
  3218.     cmfldflgs = 0;
  3219.     if (!table) {
  3220.     printf("?Keyword table missing\n");
  3221.     return(-9);
  3222.     }
  3223.     tl = (int)strlen(tok);
  3224.  
  3225.     inword = xc = cc = 0;        /* Clear character counters. */
  3226.     cmswitch = pmsg & 4;        /* Flag for parsing a switch */
  3227.  
  3228.     debug(F101,"cmkey: pmsg","",pmsg);
  3229.     debug(F101,"cmkey: cmflgs","",cmflgs);
  3230.     debug(F101,"cmkey: cmswitch","",cmswitch);
  3231.     /* debug(F101,"cmkey: cmdbuf","",cmdbuf);*/
  3232.  
  3233.     ppvnambuf[0] = NUL;
  3234.  
  3235.     if ((zz = cmflgs) == 1) {        /* Command already entered? */
  3236.     if (setatm(xdef,0) < 0) {    /* Yes, copy default into atom buf */
  3237.         printf("?Default too long\n");
  3238.         return(-9);
  3239.     }
  3240.         rtimer();             /* Reset timer */
  3241.     } else {                 /* Otherwise get a command word */
  3242.         rtimer();             /* Reset timer */
  3243.     if (pmsg & 8)             /* 8 is for parsing HELP tokens */
  3244.       zz = gtword(4);
  3245.     else
  3246.       zz = gtword((pmsg == 4) ? 1 : 0);
  3247.     }
  3248.  
  3249.     debug(F101,"cmkey table length","",n);
  3250.     debug(F101,"cmkey cmflgs","",cmflgs);
  3251.     debug(F101,"cmkey cc","",cc);
  3252.  
  3253.     while (1) {
  3254.     xc += cc;
  3255.     debug(F111,"cmkey gtword xc",atmbuf,xc);
  3256.     debug(F101,"cmkey gtword zz","",zz);
  3257.  
  3258.     switch (zz) {
  3259.       case -10:            /* Timeout */
  3260.         if (gtimer() < timelimit) {
  3261.         if (pmsg & 8)        /* 8 is for parsing HELP tokens */
  3262.           zz = gtword(4);
  3263.         else
  3264.           zz = gtword((pmsg == 4) ? 1 : 0);
  3265.         continue;
  3266.         } else {
  3267. #ifdef IKSD
  3268.                 extern int inserver;
  3269.                 if (inserver) {
  3270.                     printf("\r\nIKSD IDLE TIMEOUT: %d sec\r\n", timelimit);
  3271.                     doexit(GOOD_EXIT,0);
  3272.                 }
  3273. #endif /* IKSD */
  3274.         return(-10);
  3275.             }
  3276.       case -5:
  3277.         return(cmflgs = 0);
  3278.       case -9:
  3279.         printf("Command or field too long\n");
  3280.       case -4:            /* EOF */
  3281.       case -3:            /* Null Command/Quit/Timeout */
  3282.       case -2:            /* Buffer overflow */
  3283.       case -1:            /* Or user did some deleting. */
  3284.         return(cmflgs = zz);
  3285.  
  3286.  
  3287.       case 1:            /* CR */
  3288.       case 0:            /* User terminated word with space */
  3289.       case 4:            /* or switch ending in : or = */
  3290.         wordlen = cc;        /* Length if no conversion */
  3291.         if (cc == 0) {        /* Supply default if we got nothing */
  3292.         if ((wordlen = setatm(xdef,(zz == 4) ? 2 : 0)) < 0) {
  3293.             printf("?Default too long\n");
  3294.             return(-9);
  3295.         }
  3296.         }
  3297.         if (zz == 1 && cc == 0)    /* Required field missing */
  3298.           return(-3);
  3299.  
  3300.         if (f) {            /* If a conversion function is given */
  3301.         char * p2;
  3302.         zq = atxbuf;        /* apply it */
  3303.         p2 = atxbuf;
  3304.         atxn = CMDBL;
  3305.         if ((*f)(atmbuf,&zq,&atxn) < 0) return(-2);
  3306.         debug(F110,"cmkey atxbuf after *f",atxbuf,0);
  3307.         if (!*p2)        /* Supply default if we got nothing */
  3308.           p2 = xdef;
  3309.         ckstrncpy(ppvnambuf,atmbuf,PPVLEN);
  3310.         if ((wordlen = setatm(p2,(zz == 4) ? 2 : 0)) < 0) {
  3311.             printf("Evaluated keyword too long\n");
  3312.             return(-9);
  3313.         }
  3314. #ifdef M_UNGW
  3315.         /*
  3316.           This bit lets us save more than one "word".
  3317.           For example, "define \%x echo one two three", "\%x".
  3318.           It works too, but it breaks labels, and therefore
  3319.           WHILE and FOR loops, etc.
  3320.         */
  3321.         if (p2[wordlen] >= SP) {
  3322.             p2 += wordlen;
  3323.             while (*p2 == SP) p2++;
  3324.             if (*p2) {
  3325.             ungword();
  3326.             pp = p2;
  3327.             }
  3328.         }
  3329. #endif /* M_UNGW */
  3330.         }
  3331. #ifdef COMMENT                /* ^^^ */
  3332.         if (cmswitch && *atmbuf != '/') {
  3333.         if (pmsg & 1) {
  3334.             bleep(BP_FAIL);
  3335.                     printf("?Not a switch - %s\n",atmbuf);
  3336.         }
  3337.         cmflgs = -2;
  3338.         return(-6);
  3339.         }
  3340. #endif    /* COMMENT */
  3341.         if (cmswitch) {
  3342.         int i;
  3343.         for (i = 0; i < wordlen; i++) {
  3344.             if (atmbuf[i] == ':' || atmbuf[i] == '=') {
  3345.             brkchar = atmbuf[i];
  3346.             atmbuf[i] = NUL;
  3347.             break;
  3348.             }
  3349.         }
  3350.         }
  3351.  
  3352. #ifdef TOKPRECHECK
  3353. /* This was an effective optimization but it breaks sometimes on labels. */
  3354.         if (tl && !isalpha(atmbuf[0])) { /* Precheck for token */
  3355.         for (i = 0; i < tl; i++) { /* Save function call to ckstrchr */
  3356.             if (tok[i] == atmbuf[0]) {
  3357.             debug(F000,"cmkey token:",atmbuf,*atmbuf);
  3358.             ungword();  /* Put back the following word */
  3359.             return(-5); /* Special return code for token */
  3360.             }
  3361.         }
  3362.         }
  3363. #endif /* TOKPRECHECK */
  3364.  
  3365.         y = lookup(table,atmbuf,n,&z); /* Look up word in the table */
  3366.         debug(F111,"cmkey lookup",atmbuf,y);
  3367.         debug(F101,"cmkey zz","",zz);
  3368.         debug(F101,"cmkey cmflgs","",cmflgs);
  3369.         debug(F101,"cmkey crflag","",crflag);
  3370.         switch (y) {
  3371.           case -3:            /* Nothing to look up */
  3372.         break;
  3373.           case -2:            /* Ambiguous */
  3374.         cmflgs = -2;
  3375.         if (pmsg & 1) {
  3376.             bleep(BP_FAIL);
  3377.                     printf("?Ambiguous - %s\n",atmbuf);
  3378.             return(-9);
  3379.         }
  3380.         return(-2);
  3381.           case -1:            /* Not found at all */
  3382. #ifndef TOKPRECHECK
  3383.         if (tl) {
  3384.             for (i = 0; i < tl; i++) /* Check for token */
  3385.               if (tok[i] == *atmbuf) { /* Got one */
  3386.               debug(F000,"cmkey token:",atmbuf,*atmbuf);
  3387.               ungword();  /* Put back the following word */
  3388.               return(-5); /* Special return code for token */
  3389.               }
  3390.         }
  3391. #endif /* TOKPRECHECK */
  3392.  
  3393.         if (tl == 0) {        /* No tokens were included */
  3394. #ifdef OS2
  3395.             /* In OS/2 and Windows, allow for a disk letter like DOS */
  3396.             if (isalpha(*atmbuf) && *(atmbuf+1) == ':')
  3397.               return(-7);
  3398. #endif /* OS2 */
  3399.             if ((pmsg & 1) && !quiet) {
  3400.             bleep(BP_FAIL);
  3401.             printf("?No keywords match - %s\n",atmbuf); /* cmkey */
  3402.             }
  3403.             return(cmflgs = -9);
  3404.         } else {
  3405.             if (cmflgs == 1 || cmswitch) /* cmkey2 or cmswi */
  3406.               return(cmflgs = -6);
  3407.             else
  3408.               return(cmflgs = -2);
  3409.             /* The -6 code is to let caller try another table */
  3410.         }
  3411.         break;
  3412.           default:
  3413. #ifdef CK_RECALL
  3414.         if (test(table[z].flgs,CM_NOR)) no_recall = 1;
  3415. #endif /* CK_RECALL */
  3416.         if (zz == 4)
  3417.           swarg = 1;
  3418.         cmkwflgs = table[z].flgs;
  3419.         break;
  3420.         }
  3421.         return(y);
  3422.  
  3423.       case 2:            /* User terminated word with ESC */
  3424.         debug(F101,"cmkey Esc cc","",cc);
  3425.             if (cc == 0) {
  3426.         if (*xdef != NUL) {     /* Nothing in atmbuf */
  3427.             printf("%s ",xdef); /* Supply default if any */
  3428. #ifdef GEMDOS
  3429.             fflush(stdout);
  3430. #endif /* GEMDOS */
  3431.             addbuf(xdef);
  3432.             if (setatm(xdef,0) < 0) {
  3433.             printf("?Default too long\n");
  3434.             return(-9);
  3435.             }
  3436.             inword = cmflgs = 0;
  3437.             debug(F111,"cmkey: default",atmbuf,cc);
  3438.         } else {
  3439.             debug(F101,"cmkey Esc pmsg","",0);
  3440. #ifdef COMMENT
  3441. /*
  3442.   Chained FDBs...  The idea is that this function might not have a default,
  3443.   but the next one might.  But if it doesn't, there is no way to come back to
  3444.   this one.  To be revisited later...
  3445. */
  3446.             if (xcmfdb)        /* Chained fdb -- try next one */
  3447.               return(-3);
  3448. #endif /* COMMENT */
  3449.             if (pmsg & (1|4)) {    /* So for now just beep */
  3450.             bleep(BP_WARN);
  3451.             }
  3452.             break;
  3453.         }
  3454.             }
  3455.         if (f) {            /* If a conversion function is given */
  3456.         char * pp;
  3457.         zq = atxbuf;        /* apply it */
  3458.         pp = atxbuf;
  3459.         atxn = CMDBL;
  3460.         if ((*f)(atmbuf,&zq,&atxn) < 0)
  3461.           return(-2);
  3462.         if (!*pp)
  3463.           pp = xdef;
  3464.         if (setatm(pp,0) < 0) {
  3465.             printf("Evaluated keyword too long\n");
  3466.             return(-9);
  3467.         }
  3468.         }
  3469.         y = lookup(table,atmbuf,n,&z); /* Something in atmbuf */
  3470.         debug(F111,"cmkey lookup y",atmbuf,y);
  3471.         debug(F111,"cmkey lookup z",atmbuf,z);
  3472.         if (y == -2 && z >= 0 && z < n) { /* Ambiguous */
  3473. #ifndef NOPARTIAL
  3474.         int j, k, len = 9999;    /* Do partial completion */
  3475.         /* Skip past any abbreviations in the table */
  3476.         for ( ; z < n; z++) {
  3477.             if ((table[z].flgs & CM_ABR) == 0)
  3478.               break;
  3479.             if (!(table[z].flgs & CM_HLP) || (pmsg & 2))
  3480.               break;
  3481.         }
  3482.         debug(F111,"cmkey partial z",atmbuf,z);
  3483.         debug(F111,"cmkey partial n",atmbuf,n);
  3484.         for (j = z+1; j < n; j++) {
  3485.             debug(F111,"cmkey partial j",table[j].kwd,j);
  3486.             if (ckstrcmp(atmbuf,table[j].kwd,cc,0))
  3487.               break;
  3488.             if (table[j].flgs & CM_ABR)
  3489.               continue;
  3490.             if ((table[j].flgs & CM_HLP) && !(pmsg & 2))
  3491.               continue;
  3492.             k = ckstrpre(table[z].kwd,table[j].kwd);
  3493.             debug(F111,"cmkey partial k",table[z].kwd,k);
  3494.             if (k < len)
  3495.               len = k; /* Length of longest common prefix */
  3496.         }
  3497.         debug(F111,"cmkey partial len",table[z].kwd,len);
  3498.         if (len != 9999 && len > cc) {
  3499.             ckstrncat(atmbuf,table[z].kwd+cc,ATMBL);
  3500.             atmbuf[len] = NUL;
  3501.             printf("%s",atmbuf+cc);
  3502.             ckstrncat(cmdbuf,atmbuf+cc,CMDBL);
  3503.             xc += (len - cc);
  3504.             cc = len;
  3505.         }
  3506. #endif /* NOPARTIAL */
  3507.         bleep(BP_WARN);
  3508.         break;
  3509.         } else if (y == -3) {
  3510.         bleep(BP_WARN);
  3511.         break;
  3512.         } else if (y == -1) {    /* Not found */
  3513.         if ((pmsg & 1) && !quiet) {
  3514.             bleep(BP_FAIL);
  3515.             printf("?No keywords match - \"%s\"\n",atmbuf);
  3516.         }
  3517.         cmflgs = -2;
  3518.         return(-9);
  3519.         }
  3520. /*
  3521.   If we found it, but it's a help-only keyword and the "help" bit is not
  3522.   set in pmsg, then not found.
  3523. */
  3524.         debug(F101,"cmkey flgs","",table[z].flgs);
  3525.         if (test(table[z].flgs,CM_HLP) && ((pmsg & 2) == 0)) {
  3526.         if ((pmsg & 1) && !quiet) {
  3527.             bleep(BP_FAIL);
  3528.             printf("?No keywords match - %s\n",atmbuf);
  3529.         }
  3530.         cmflgs = -2;
  3531.         return(-9);
  3532.         }
  3533. /*
  3534.   See if the keyword just found has the CM_ABR bit set in its flgs field, and
  3535.   if so, search forwards in the table for a keyword that has the same kwval
  3536.   but does not have CM_ABR (or CM_INV?) set, and then expand using the full
  3537.   keyword.  WARNING: This assumes that (a) keywords are in alphabetical order,
  3538.   and (b) the CM_ABR bit is set only if the the abbreviated keyword is a true
  3539.   abbreviation (left substring) of the full keyword.
  3540. */
  3541.         if (test(table[z].flgs,CM_ABR)) {
  3542.         int zz;
  3543.         for (zz = z+1; zz < n; zz++)
  3544.           if ((table[zz].kwval == table[z].kwval) &&
  3545.               (!test(table[zz].flgs,CM_ABR)) &&
  3546.               (!test(table[zz].flgs,CM_INV))) {
  3547.               z = zz;
  3548.               break;
  3549.           }
  3550.         }
  3551.         xp = table[z].kwd + cc;
  3552.         if (cmswitch && test(table[z].flgs,CM_ARG)) {
  3553. #ifdef VMS
  3554.         printf("%s=",xp);
  3555.         brkchar = '=';
  3556. #else
  3557.         printf("%s:",xp);
  3558.         brkchar = ':';
  3559. #endif /* VMS */
  3560.         } else {
  3561.         printf("%s ",xp);
  3562.         brkchar = SP;
  3563.         }
  3564. #ifdef CK_RECALL
  3565.         if (test(table[z].flgs,CM_NOR)) no_recall = 1;
  3566. #endif /* CK_RECALL */
  3567.         cmkwflgs = table[z].flgs;
  3568. #ifdef GEMDOS
  3569.         fflush(stdout);
  3570. #endif /* GEMDOS */
  3571.         addbuf(xp);
  3572.         if (cmswitch && test(table[z].flgs,CM_ARG)) {
  3573.         bp--;            /* Replace trailing space with : */
  3574. #ifdef VMS
  3575.         *bp++ = '=';
  3576. #else
  3577.         *bp++ = ':';
  3578. #endif /* VMS */
  3579.         *bp = NUL;
  3580.         np = bp;
  3581.         swarg = 1;
  3582.         }
  3583.         inword = 0;
  3584.         cmflgs = 0;
  3585.         debug(F110,"cmkey: addbuf",cmdbuf,0);
  3586.         return(y);
  3587.  
  3588.       case 3:            /* User typed "?" */
  3589.         if (f) {            /* If a conversion function is given */
  3590.         char * pp;
  3591.         zq = atxbuf;        /* do the conversion now. */
  3592.         pp = atxbuf;
  3593.         atxn = CMDBL;
  3594.         if ((*f)(atmbuf,&zq,&atxn) < 0) return(-2);
  3595.         if (setatm(pp,0) < 0) {
  3596.             printf("?Evaluated keyword too long\n");
  3597.             return(-9);
  3598.         }
  3599.         }
  3600.         y = lookup(table,atmbuf,n,&z); /* Look up what we have so far. */
  3601.         if (y == -1) {
  3602.         /*
  3603.           Strictly speaking if the main keyword table search fails,
  3604.           then we should look in the token table if one is given.
  3605.           But in practice, tokens are also included in the main
  3606.           keyword table.
  3607.         */
  3608.         cmflgs = -2;
  3609.         if ((pmsg & 1) && !quiet) {
  3610.             bleep(BP_FAIL);
  3611.             printf(" No keywords match\n");
  3612.             return(-9);
  3613.         }
  3614.         return(-2);
  3615.         }
  3616. #ifndef COMMENT
  3617.         /* This is to allow ?-help to work immediately after a token */
  3618.         /* without having to type an intermediate space */
  3619.         if (tl) {
  3620.         for (i = 0; i < tl; i++) /* Check for token */
  3621.           if (tok[i] == *atmbuf) { /* Got one */
  3622.               debug(F000,"cmkey token:",atmbuf,*atmbuf);
  3623.               ungword();    /* Put back the following word */
  3624.               cmflgs = 3;    /* Force help next time around */
  3625.               return(-5);    /* Special return code for token */
  3626.           }
  3627.         }
  3628. #endif /* COMMENT */
  3629.  
  3630.         if (*xhlp == NUL)
  3631.           printf(" One of the following:\n");
  3632.         else
  3633.           printf(" %s, one of the following:\n",xhlp);
  3634.         {
  3635.         int x;
  3636.         x = pmsg & (2|4);    /* See kwdhelp() comments */
  3637.         if (atmbuf[0])        /* If not at beginning of field */
  3638.           x |= 1;        /* also show invisibles */
  3639.         kwdhelp(table,n,atmbuf,"","",1,x);
  3640.         }
  3641. #ifndef NOSPL
  3642.         if (!havetoken) {
  3643.         extern int topcmd;
  3644.         if (tl > 0 && topcmd != XXHLP) /* This is bad... */
  3645.           printf("or a macro name (\"do ?\" for a list) ");
  3646.         }
  3647. #endif /* NOSPL */
  3648.         if (*atmbuf == NUL && !havetoken) {
  3649.         if (tl == 1)
  3650.           printf("or the token %c\n",*tok);
  3651.         else if (tl > 1)
  3652.           printf("or one of the tokens: %s\n",ckspread(tok));
  3653.         }
  3654.         printf("%s%s", cmprom, cmdbuf);
  3655.         fflush(stdout);
  3656.         break;
  3657.  
  3658.       default:
  3659.         printf("\n%d - Unexpected return code from gtword\n",zz);
  3660.         return(cmflgs = -2);
  3661.     }
  3662.     zz = (pmsg & 8) ? gtword(4) : gtword((pmsg == 4) ? 1 : 0);
  3663.     debug(F111,"cmkey gtword zz",atmbuf,zz);
  3664.     }
  3665. }
  3666.  
  3667. int
  3668. chktok(tlist) char *tlist; {
  3669.     char *p;
  3670.     p = tlist;
  3671.     while (*p != NUL && *p != *atmbuf) p++;
  3672.     return((*p) ? (int) *p : 0);
  3673. }
  3674.  
  3675. /* Routines for parsing and converting dates and times */
  3676.  
  3677. #define isdatesep(c) (ckstrchr(" -/._",c))
  3678.  
  3679. #define CMDATEBUF 1024
  3680. char cmdatebuf[CMDATEBUF+4] = { NUL, NUL };
  3681. static char * cmdatebp = cmdatebuf;
  3682. char * cmdatemsg = NULL;
  3683.  
  3684. static struct keytab timeunits[] = {
  3685.     { "days",   TU_DAYS,   0 },
  3686.     { "months", TU_MONTHS, 0 },
  3687.     { "weeks",  TU_WEEKS,  0 },
  3688.     { "wks",    TU_WEEKS,  0 },
  3689.     { "years",  TU_YEARS,  0 },
  3690.     { "yrs",    TU_YEARS,  0 }
  3691. };
  3692. static int nunits = (sizeof(timeunits) / sizeof(struct keytab));
  3693.  
  3694. #define SYM_NOW  0
  3695. #define SYM_TODA 1
  3696. #define SYM_TOMO 2
  3697. #define SYM_YEST 3
  3698.  
  3699. static struct keytab symdaytab[] = {
  3700.     { "now",       SYM_NOW,  0 },
  3701.     { "today",     SYM_TODA, 0 },
  3702.     { "tomorrow",  SYM_TOMO, 0 },
  3703.     { "yesterday", SYM_YEST, 0 }
  3704. };
  3705. static int nsymdays = (sizeof(symdaytab) / sizeof(struct keytab));
  3706.  
  3707. static struct keytab daysofweek[] = {
  3708.     { "Friday",    5, 0 },
  3709.     { "Monday",    1, 0 },
  3710.     { "Saturday",  6, 0 },
  3711.     { "Sunday",    0, 0 },
  3712.     { "Thursday",  4, 0 },
  3713.     { "Tuesday",   2, 0 },
  3714.     { "Wednesday", 3, 0 }
  3715. };
  3716.  
  3717. static struct keytab usatz[] = {    /* RFC 822 timezones  */
  3718.     { "cdt",  5, 0 },            /* Values are GMT offsets */
  3719.     { "cst",  6, 0 },
  3720.     { "edt",  4, 0 },
  3721.     { "est",  5, 0 },
  3722.     { "gmt",  0, 0 },
  3723.     { "mdt",  6, 0 },
  3724.     { "mst",  7, 0 },
  3725.     { "pdt",  7, 0 },
  3726.     { "pst",  8, 0 },
  3727.     { "utc",  0, 0 },
  3728.     { "zulu", 0, 0 }
  3729. };
  3730. static int nusatz = (sizeof(usatz) / sizeof(struct keytab));
  3731.  
  3732.  
  3733. /*  C M C V T D A T E  --  Converts free-form date to standard form.  */
  3734.  
  3735. /*
  3736.    Call with
  3737.      s = pointer to free-format date, time, or date and time.
  3738.      t = 0: return time only if time was given in s.
  3739.      t = 1: always return time (00:00:00 if no time given in s).
  3740.      t = 2: allow time to be > 24:00:00.
  3741.    Returns:
  3742.      NULL on failure;
  3743.      Pointer to "yyyymmdd hh:mm:ss" (local date-time) on success.
  3744. */
  3745.  
  3746. /*
  3747.   Before final release the following long lines should be wrapped.
  3748.   Until then we leave them long since wrapping them wrecks EMACS's
  3749.   C indentation.
  3750. */
  3751.  
  3752. /* asctime pattern */
  3753. static char * atp1 = "[A-Z][a-z][a-z] [A-Z][a-z][a-z] [ 0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9][0-9][0-9][0-9]";
  3754.  
  3755. /* asctime pattern with timezone */
  3756. static char * atp2 = "[A-Z][a-z][a-z] [A-Z][a-z][a-z] [ 0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [A-Z][A-Z][A-Z] [0-9][0-9][0-9][0-9]";
  3757.  
  3758. #define DATEBUFLEN 127
  3759. #define YYYYMMDD 12
  3760.  
  3761. #define isleap(y) (((y) % 4 == 0 && (y) % 100 != 0) || (y) % 400 == 0)
  3762. static int mdays[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  3763.  
  3764. #define NEED_DAYS 1
  3765. #define NEED_HRS  2
  3766. #define NEED_MINS 3
  3767. #define NEED_SECS 4
  3768. #define NEED_FRAC 5
  3769.  
  3770. #define DELTABUF 256
  3771. static char deltabuf[DELTABUF];
  3772. static char * deltabp = deltabuf;
  3773.  
  3774. char *
  3775. cmdelta(yy, mo, dd, hh, mm, ss, sign, dyy, dmo, ddd, dhh, dmm, dss)
  3776.     int yy, mo, dd, hh, mm, ss, sign, dyy, dmo, ddd, dhh, dmm, dss;
  3777. /* cmdelta */ {
  3778.     int zyy, zmo, zdd, zhh, zmm, zss;
  3779.     long t1, t2, t3, t4;
  3780.     long d1 = 0, d2, d3;
  3781.     char datebuf[DATEBUFLEN+1];
  3782.  
  3783. #ifdef DEBUG
  3784.     if (deblog) {
  3785.     debug(F101,"cmdelta yy","",yy);
  3786.     debug(F101,"cmdelta mo","",mo);
  3787.     debug(F101,"cmdelta dd","",dd);
  3788.     debug(F101,"cmdelta hh","",hh);
  3789.     debug(F101,"cmdelta mm","",mm);
  3790.     debug(F101,"cmdelta ss","",ss);
  3791.     debug(F101,"cmdelta sign","",sign);
  3792.     debug(F101,"cmdelta dyy","",dyy);
  3793.     debug(F101,"cmdelta dmo","",dmo);
  3794.     debug(F101,"cmdelta ddd","",ddd);
  3795.     debug(F101,"cmdelta dhh","",dhh);
  3796.     debug(F101,"cmdelta dmm","",dmm);
  3797.     debug(F101,"cmdelta dss","",dss);
  3798.     }
  3799. #endif /* DEBLOG */
  3800.  
  3801.     if (yy < 0 || yy > 9999) {
  3802.     makestr(&cmdatemsg,"Base year out of range");
  3803.     debug(F111,"cmdelta",cmdatemsg,-1);
  3804.     return(NULL);
  3805.     }
  3806.     if (mo < 1 || mo > 12) {
  3807.     makestr(&cmdatemsg,"Base month out of range");
  3808.     debug(F111,"cmdelta",cmdatemsg,-1);
  3809.     return(NULL);
  3810.     }
  3811.     if (dd < 1 || dd > mdays[mo]) {
  3812.     makestr(&cmdatemsg,"Base day out of range");
  3813.     debug(F111,"cmdelta",cmdatemsg,-1);
  3814.     return(NULL);
  3815.     }
  3816.     if (hh < 0 || hh > 23) {
  3817.     makestr(&cmdatemsg,"Base hour out of range");
  3818.     debug(F111,"cmdelta",cmdatemsg,-1);
  3819.     return(NULL);
  3820.     }
  3821.     if (mm < 0 || mm > 59) {
  3822.     makestr(&cmdatemsg,"Base minute out of range");
  3823.     debug(F111,"cmdelta",cmdatemsg,-1);
  3824.     return(NULL);
  3825.     }
  3826.     if (ss < 0 || ss > 60) {
  3827.     makestr(&cmdatemsg,"Base second out of range");
  3828.     debug(F111,"cmdelta",cmdatemsg,-1);
  3829.     return(NULL);
  3830.     }
  3831.     sign = (sign < 0) ? -1 : 1;
  3832.     if (dmo != 0) {
  3833.         if (sign > 0) {
  3834.             mo += (sign * dmo);
  3835.             if (mo > 12) {
  3836.                 yy += mo / 12;
  3837.                 mo = mo % 12;
  3838.             }
  3839.         } else if (sign < 0) {
  3840.             while (dmo > 12) {
  3841.                 yy--;
  3842.                 dmo -= 12;
  3843.             }
  3844.             if (dmo < mo) {
  3845.                 mo -= dmo;
  3846.             } else {
  3847.                 yy--;
  3848.                 mo = 12 - (dmo - mo);
  3849.             }
  3850.         }
  3851.     }
  3852.     if (dyy != 0) {
  3853.     yy += (sign * dyy);
  3854.     if (yy > 9999 || yy < 0) {
  3855.         makestr(&cmdatemsg,"Result year out of range");
  3856.         debug(F111,"cmdelta",cmdatemsg,-1);
  3857.         return(NULL);
  3858.     }
  3859.     }
  3860.     sprintf(datebuf,"%04d%02d%02d %02d:%02d:%02d",yy,mo,dd,hh,mm,ss);
  3861.     d1 = mjd(datebuf);
  3862.     debug(F111,"cmdelta mjd",datebuf,d1);    
  3863.  
  3864.     t1 = hh * 3600 + mm * 60 + ss;    /* Base time to secs since midnight */
  3865.     t2 = dhh * 3600 + dmm * 60 + dss;    /* Delta time, ditto */
  3866.     t3 = t1 + (sign * t2);        /* Get sum (or difference) */
  3867.     
  3868.     d2 = (sign * ddd);            /* Delta days */
  3869.     d2 += t3 / 86400L;
  3870.  
  3871.     t4 = t3 % 86400L;            /* Fractional part of day */
  3872.     if (t4 < 0) {            /* If negative */
  3873.     d2--;                /* one less delta day */
  3874.     t4 += 86400L;            /* get positive seconds */
  3875.     }
  3876.     hh = (int) (t4 / 3600L);
  3877.     mm = (int) (t4 % 3600L) / 60;
  3878.     ss = (int) (t4 % 3600L) % 60;
  3879.  
  3880.     sprintf(datebuf,"%s %02d:%02d:%02d", mjd2date(d1+d2),hh,mm,ss);
  3881.     {
  3882.     int len, k, n;
  3883.     char * p;
  3884.     len = strlen(datebuf);
  3885.     k = deltabp - (char *)deltabuf;    /* Space used */
  3886.     n = DELTABUF - k - 1;        /* Space left */
  3887.     if (n < len) {            /* Not enough? */
  3888.         deltabp = deltabuf;        /* Wrap around */
  3889.         n = DELTABUF;
  3890.     }
  3891.     ckstrncpy(deltabp,datebuf,n);
  3892.     p = deltabp;
  3893.     deltabp += len + 1;
  3894.     return(p);
  3895.     }
  3896. }
  3897.  
  3898.  
  3899. /* Convert Delta Time to Seconds */
  3900.  
  3901. int
  3902. delta2sec(s,result) char * s; long * result; {
  3903.     long ddays = 0L, zz;
  3904.     int dsign = 1, dhours = 0, dmins = 0, dsecs = 0, units;
  3905.     int state = NEED_DAYS;
  3906.     char *p, *p2, *p3, c = 0;
  3907.     char buf[64];
  3908.  
  3909.     if (!s) s = "";
  3910.     if (!*s)
  3911.       return(-1);
  3912.     if ((int)strlen(s) > 63)
  3913.       return(-1);
  3914.     ckstrncpy(buf,s,64);
  3915.     p = buf;
  3916.  
  3917.     if (*p != '+' && *p != '-')
  3918.       return(-1);
  3919.  
  3920.     if (*p++ == '-')
  3921.       dsign = -1;
  3922.     while (*p == SP)            /* Skip intervening spaces */
  3923.       p++;
  3924.  
  3925.     while (state) {            /* FSA to parse delta time */
  3926.     if (state < 0 || !isdigit(*p))
  3927.       return(-1);
  3928.     p2 = p;                /* Get next numeric field */
  3929.     while (isdigit(*p2))
  3930.       p2++;
  3931.     c = *p2;            /* And break character */
  3932.     *p2 = NUL;            /* Terminate the number */
  3933.     switch (state) {        /* Interpret according to state */
  3934.       case NEED_DAYS:        /* Initial */
  3935.         if ((c == '-') ||        /* VMS format */
  3936.         ((c == 'd' || c == 'D')
  3937.          && !isalpha(*(p2+1)))) { /* Days */
  3938.         ddays = atol(p);
  3939.         if (!*(p2+1))            
  3940.           state = 0;
  3941.         else            /* if anything is left */
  3942.           state = NEED_HRS;    /* now we want hours. */
  3943.         } else if (c == ':') {    /* delimiter is colon */
  3944.         dhours = atoi(p);    /* so it's hours */
  3945.         state = NEED_MINS;    /* now we want minutes */
  3946.         } else if (!c) {        /* end of string */
  3947.         dhours = atoi(p);    /* it's still hours */
  3948.         state = 0;        /* and we're done */
  3949.         } else if (isalpha(c) || c == SP) {
  3950.         if (c == SP) {        /* It's a keyword? */
  3951.             p2++;        /* Skip spaces */
  3952.             while (*p2 == SP)
  3953.               p2++;
  3954.         } else {        /* or replace first letter */
  3955.             *p2 = c;
  3956.         }
  3957.         p3 = p2;        /* p2 points to beginning of keyword */
  3958.         while (isalpha(*p3))    /* Find end of keyword */
  3959.           p3++;
  3960.         c = *p3;        /* NUL it out so we can look it up */
  3961.         if (*p3)        /* p3 points to keyword terminator */
  3962.           *p3 = NUL;
  3963.         if ((units = lookup(timeunits,p2,nunits,NULL)) < 0)
  3964.           return(-1);
  3965.         *p2 = NUL;        /* Re-terminate the number */
  3966.         *p3 = c;
  3967.         while (*p3 == SP)    /* Point at field after units */
  3968.           p3++;
  3969.         p2 = p3;
  3970.         switch (units) {
  3971.           case TU_DAYS:
  3972.             ddays = atol(p);
  3973.             break;
  3974.           default:
  3975.             return(-1);
  3976.         }
  3977.         if (*p2) {
  3978.             state = NEED_HRS;
  3979.             p2--;
  3980.         } else
  3981.           state = 0;
  3982.         } else {            /* Anything else */
  3983.         state = -1;        /* is an error */
  3984.         }
  3985.         break;
  3986.       case NEED_HRS:        /* Looking for hours */
  3987.         if (c == ':') {
  3988.         dhours = atoi(p);
  3989.         state = NEED_MINS;
  3990.         } else if (!c) {
  3991.         dhours = atoi(p);
  3992.         state = 0;
  3993.         } else {
  3994.         state = -1;
  3995.         }
  3996.         break;
  3997.       case NEED_MINS:        /* Looking for minutes */
  3998.         if (c == ':') {
  3999.         dmins = atoi(p);
  4000.         state = NEED_SECS;
  4001.         } else if (!c) {
  4002.         dmins = atoi(p);
  4003.         state = 0;
  4004.         } else {
  4005.         state = -1;
  4006.         }
  4007.         break;
  4008.       case NEED_SECS:        /* Looking for seconds */
  4009.         if (c == '.') {
  4010.         dsecs = atoi(p);
  4011.         state = NEED_FRAC;
  4012.         } else if (!c) {
  4013.         dsecs = atoi(p);
  4014.         state = 0;
  4015.         } else {
  4016.         state = -1;
  4017.         }
  4018.         break;
  4019.       case NEED_FRAC:        /* Fraction of second */
  4020.         if (!c && rdigits(p)) {
  4021.         if (*p > '4')
  4022.           dsecs++;
  4023.         state = 0;
  4024.         } else {
  4025.         state = -1;
  4026.         }
  4027.         break;
  4028.     }
  4029.     if (c)                /* next field if any */
  4030.       p = p2 + 1;
  4031.     }
  4032.     if (state < 0)
  4033.       return(-1);
  4034.  
  4035.     /* if days > 24854 and sizeof(long) == 32 we overflow */
  4036.  
  4037.     zz = ddays * 86400L;
  4038.     if (zz < 0L)            /* This catches it */
  4039.       return(-2);
  4040.     zz += dhours * 3600L + dmins * 60L + dsecs;
  4041.     zz *= dsign;
  4042.     *result = zz;
  4043.     return(0);
  4044. }
  4045.  
  4046.  
  4047. char *
  4048. cmcvtdate(s,t) char * s; int t; {
  4049.     int x, i, j, k, hh, mm, ss, ff, pmflag = 0, nodate = 0, len, dow;
  4050.     int units, isgmt = 0, gmtsign = 0, d = 0, state = 0, nday;
  4051.     int kn = 0, ft[8], isletter = 0, f2len = 0;
  4052.  
  4053.     int zhh = 0;            /* Timezone adjustments */
  4054.     int zmm = 0;
  4055.     int zdd = 0;
  4056.  
  4057.     int dsign = 1;            /* Delta-time adjustments */
  4058.     int ddays = 0;
  4059.     int dmonths = 0;
  4060.     int dyears = 0;
  4061.     int dhours = 0;
  4062.     int dmins = 0;
  4063.     int dsecs = 0;
  4064.     int havedelta = 0;
  4065.  
  4066.     char * fld[8], * p = "", * p2, * p3; /* Assorted buffers and pointers  */
  4067.     char * s2, * s3;
  4068.     char * year = NULL, * month = NULL, * day = NULL;
  4069.     char * hour = "00", * min = "00", * sec = "00";
  4070.     char datesep = 0;
  4071.     char tmpbuf[8];
  4072.     char xbuf[DATEBUFLEN+1];
  4073.     char ybuf[DATEBUFLEN+1];
  4074.     char zbuf[DATEBUFLEN+1];
  4075.     char yyyymmdd[YYYYMMDD];
  4076.     char dbuf[26];
  4077.     char daybuf[3];
  4078.     char monbuf[3];
  4079.     char yearbuf[5];
  4080.     char timbuf[16], *tb, cc;
  4081.     char * dp = NULL;            /* Result pointer */
  4082.  
  4083.     if (!s) s = "";
  4084.     tmpbuf[0] = NUL;
  4085.  
  4086.     while (*s == SP) s++;        /* Gobble any leading blanks */
  4087.     if (isalpha(*s))            /* Remember if 1st char is a letter */
  4088.       isletter = 1;
  4089.  
  4090.     len = strlen(s);
  4091.     debug(F110,"cmcvtdate",s,len);
  4092.     if (len == 0) {            /* No arg - return current date-time */
  4093.     dp = ckdate();
  4094.     goto xcvtdate;
  4095.     }
  4096.     if (len > DATEBUFLEN) {        /* Check length of arg */
  4097.     makestr(&cmdatemsg,"Date-time string too long");
  4098.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4099.     return(NULL);
  4100.     }
  4101.     hh = 0;                /* Init time to 00:00:00.0 */
  4102.     mm = 0;
  4103.     ss = 0;
  4104.     ff = 0;
  4105.     ztime(&p);
  4106.     if (!p)
  4107.       p  = "";
  4108.     if (*p) {                /* Init time to current time */
  4109.     x = ckstrncpy(dbuf,p,26);
  4110.     if (x > 17) {
  4111.         hh = atoi(&dbuf[11]);
  4112.         mm = atoi(&dbuf[14]);
  4113.         ss = atoi(&dbuf[17]);
  4114.     }
  4115.     }
  4116.     ckstrncpy(yyyymmdd,zzndate(),YYYYMMDD); /* Init date to current date */
  4117.     ckstrncpy(yearbuf,yyyymmdd,5);
  4118.     ckstrncpy(monbuf,&yyyymmdd[4],3);
  4119.     ckstrncpy(daybuf,&yyyymmdd[6],3);
  4120.     year = yearbuf;
  4121.     month = monbuf;
  4122.     day = daybuf;
  4123.     nday = atoi(daybuf);
  4124.     ckstrncpy(xbuf,s,DATEBUFLEN);    /* Make a local copy we can poke */
  4125.     s = xbuf;                /* Point to it */
  4126.     s[len] = NUL;
  4127.     if (s[0] == ':') {
  4128.     p = s;
  4129.     goto dotime;
  4130.     }
  4131.     /* Special preset formats... */
  4132.  
  4133.     if (len >= 14) {            /* FTP MDTM all-numeric date */
  4134.     char c;
  4135.     c = s[14];            /* e.g. 19980615100045.014 */
  4136.     s[14] = NUL;
  4137.     x = rdigits(s);
  4138.     s[14] = c;
  4139.     if (x) {
  4140.         ckstrncpy(yyyymmdd,s,8+1);
  4141.         year = NULL;
  4142.         p = &s[8];
  4143.         goto dotime;
  4144.     }
  4145.     }
  4146.     x = 0;                /* Becomes > 0 for asctime format */
  4147.     if (isalpha(s[0])) {
  4148.     if (len == 24) {        /* Asctime format? */
  4149.         /* Sat Jul 14 15:57:32 2001 */
  4150.         x = ckmatch(atp1,s,0,0);
  4151.         debug(F111,"cmcvtdate asctime",s,x);
  4152.     } else if (len == 28) {        /* Or Asctime plus timezone? */
  4153.         /* Sat Jul 14 15:15:39 EDT 2001 */
  4154.         x = ckmatch(atp2,s,0,0);
  4155.         debug(F111,"cmcvtdate asctime+timezone",s,x);
  4156.     }
  4157.     }
  4158.     if (x > 0) {            /* Asctime format */
  4159.         int xx;
  4160.         strncpy(yearbuf,s + len - 4,4);
  4161.         yearbuf[4] = NUL;
  4162.         for (i = 0; i < 3; i++)
  4163.           tmpbuf[i] = s[i+4];
  4164.         tmpbuf[3] = NUL;
  4165.     if ((xx = lookup(cmonths,tmpbuf,12,NULL)) < 0) {
  4166.         makestr(&cmdatemsg,"Invalid month");
  4167.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4168.         return(NULL);
  4169.     }
  4170.         debug(F101,"cmcvtdate asctime month","",xx);
  4171.         monbuf[0] = (xx / 10) + '0'; 
  4172.         monbuf[1] = (xx % 10) + '0'; 
  4173.         monbuf[2] = NUL;
  4174.         daybuf[0] = (s[8] == ' ' ? '0' : s[8]);
  4175.         daybuf[1] = s[9];
  4176.         daybuf[2] = NUL;
  4177.     xbuf[0] = SP;
  4178.         for (i = 11; i < 19; i++)
  4179.           xbuf[i-10] = s[i];
  4180.         xbuf[9] = NUL;
  4181.     ckmakmsg(zbuf,18,yearbuf,monbuf,daybuf,xbuf);
  4182.     debug(F110,"cmcvtdate asctime ok",zbuf,0);
  4183.     if (len == 24) {
  4184.         dp = zbuf;
  4185.         goto xcvtdate;
  4186.     } else {
  4187.         int n;
  4188.         n = ckmakmsg(ybuf,DATEBUFLEN-4,zbuf," ",NULL,NULL);
  4189.         ybuf[n++] = s[20];
  4190.         ybuf[n++] = s[21];
  4191.         ybuf[n++] = s[22];
  4192.         ybuf[n++] = NUL;
  4193.         ckstrncpy(xbuf,ybuf,DATEBUFLEN);
  4194.         s = xbuf;
  4195.         isletter = 0;
  4196.     }
  4197.     }
  4198.  
  4199. /* Check for day of week */
  4200.  
  4201.     p = s;
  4202.     while (*p == SP) p++;
  4203.     dow = -1;
  4204.     if (*p) {
  4205.     p2 = p;
  4206.     cc = NUL;
  4207.     while (1) {
  4208.         if (*p2 == ',' || *p2 == SP || !*p2) {
  4209.         cc = *p2;        /* Save break char */
  4210.         *p2 = NUL;        /* NUL it out */
  4211.         p3 = p2;        /* Remember this spot */
  4212.         if ((dow = lookup(daysofweek,p,7,NULL)) > -1) {
  4213.             debug(F111,"cmcvtdate dow",p,dow);
  4214.             s = p2;
  4215.             if (cc == ',' || cc == SP) { /* Point to next field */
  4216.             s++;
  4217.             while (*s == SP) s++;
  4218.             }
  4219.             p = s;
  4220.             debug(F111,"cmcvtdate dow new p",p,dow);
  4221.             break;
  4222.         } else if (isalpha(*p) && cc == ',') {
  4223.             makestr(&cmdatemsg,"Unrecognized day of week");
  4224.             debug(F111,"cmcvtdate",cmdatemsg,-1);
  4225.             return(NULL);
  4226.         } else {
  4227.             *p3 = cc;
  4228.             break;
  4229.         }
  4230.         }
  4231.         p2++;
  4232.     }
  4233.     }
  4234.     len = strlen(s);        /* Update length */
  4235.     debug(F111,"cmcvtdate s",s,len);
  4236.  
  4237.     debug(F111,"cmcvtdate dow",s,dow);
  4238.     if (dow > -1) {            /* Have a day-of-week number */
  4239.     long zz; int n, j;
  4240.     zz = mjd(zzndate());        /* Get today's MJD */
  4241.     debug(F111,"cmcvtdate zz","",zz);
  4242.     j = (((int)(zz % 7L)) + 3) % 7; /* Today's day-of-week number */
  4243.     debug(F111,"cmcvtdate j","",j);
  4244.     hh = 0;                /* Init time to midnight */
  4245.     mm = 0;
  4246.     ss = 0;
  4247.     if (j == dow) {
  4248.         ckstrncpy(yyyymmdd,zzndate(),YYYYMMDD);
  4249.         year = NULL;
  4250.     } else {
  4251.         n = dow - j;        /* Days from now */
  4252.         if (dow < j)
  4253.           n += 7;
  4254.         if (n < 0) n += 7;        /* Add to MJD */
  4255.         zz += n;
  4256.         ckstrncpy(yyyymmdd,mjd2date(zz),YYYYMMDD); /* New date */
  4257.         year = NULL;
  4258.     }
  4259.     debug(F111,"cmcvtdate A",yyyymmdd,len);
  4260.     if (len == 0) {            /* No more fields after this */
  4261.         ckmakmsg(zbuf,18,yyyymmdd," 00:00:00",NULL,NULL);
  4262.         dp = zbuf;
  4263.         goto xcvtdate;
  4264.     }
  4265.     isletter = 0;
  4266.     if (rdigits(p) && len < 8)    /* Next field is time? */
  4267.       goto dotime;            /* If so go straight to time section */
  4268.     if (isdigit(*p)) {
  4269.         if (*(p+1) == ':')
  4270.           goto dotime;
  4271.         else if (isdigit(*(p+1)) && (*(p+2) == ':'))
  4272.           goto dotime;
  4273.     }
  4274.     }
  4275.     debug(F111,"cmcvtdate B s",s,dow);
  4276.     debug(F111,"cmcvtdate B p",p,dow);
  4277.  
  4278.     if (*s == '+' || *s == '-') {    /* Delta time only - skip ahead. */
  4279.     p = s;
  4280.     goto delta;
  4281.     }
  4282. #ifdef COMMENT
  4283. /*
  4284.   What is the purpose of this?  It breaks parsing of email dates like
  4285.   "Wed, 13 Feb 2002 17:43:02 -0800 (PST)".  Removing this code fixes the
  4286.   problem and Kermit still passes the 'dates' script.
  4287.   - fdc, Sat Nov 26 10:52:45 2005.
  4288. */
  4289.     if (dow > -1) {
  4290.     /* Day of week given followed by something that is not a time */
  4291.     /* or a delta so it can't be valid */
  4292.     makestr(&cmdatemsg,"Invalid tokens after day of week");
  4293.     debug(F111,"cmcvtdate fail",cmdatemsg,-1);
  4294.     return(NULL);
  4295.     }
  4296. #endif    /* COMMENT */
  4297.  
  4298.     /* Handle "today", "yesterday", "tomorrow", and +/- n units */
  4299.  
  4300.     if (ckstrchr("TtYyNn",s[0])) {
  4301.     int i, k, n, minus = 0;
  4302.     char c;
  4303.     long jd;
  4304.     jd = mjd(ckdate());
  4305.     debug(F111,"cmcvtdate mjd",s,jd);
  4306.  
  4307.     /* Symbolic date: TODAY, TOMORROW, etc...? */
  4308.  
  4309.     s2 = s;                /* Find end of keyword */
  4310.     i = 0;
  4311.     while (isalpha(*s2)) {        /* and get its length */
  4312.         i++;
  4313.         s2++;
  4314.     }
  4315.     c = *s2;            /* Zap but save delimiter */
  4316.     *s2 = NUL;
  4317.     k = lookup(symdaytab,s,nsymdays,NULL); /* Look up keyword */
  4318.     *s2 = c;            /* Replace delimiter */
  4319.     if (k < 0)            /* Keyword not found */
  4320.       goto normal;
  4321.     s3 = &s[i];
  4322.     while (*s3 == SP)        /* Skip whitespace */
  4323.       s3++;
  4324.     if (*s3 == '_' || *s3 == ':')
  4325.       s3++;
  4326.  
  4327.     switch (k) {            /* Have keyword */
  4328.       case SYM_NOW:            /* NOW */
  4329.         ckstrncpy(ybuf,ckdate(),DATEBUFLEN);
  4330.         ckstrncpy(yyyymmdd,ybuf,YYYYMMDD);
  4331.         year = NULL;
  4332.         if (*s3) {            /* No overwriting current time. */
  4333.         ckstrncat(ybuf," ",DATEBUFLEN);
  4334.         ckstrncat(ybuf,s3,DATEBUFLEN);
  4335.         }
  4336.         break;
  4337.       default:            /* Yesterday, Today, and Tomorrow */
  4338.         if (k == SYM_TOMO) {    /* TOMORROW */
  4339.         strncpy(ybuf,mjd2date(jd+1),8);
  4340.         } else if (k == SYM_YEST) {    /* YESTERDAY */
  4341.         strncpy(ybuf,mjd2date(jd-1),8);
  4342.         } else {            /* TODAY */
  4343.         strncpy(ybuf,ckdate(),8);
  4344.         }
  4345.         strncpy(ybuf+8," 00:00:00",DATEBUFLEN-8); /* Default time is 0 */
  4346.         ckstrncpy(yyyymmdd,ybuf,YYYYMMDD);
  4347.         year = NULL;
  4348.         if (*s3) {            /* If something follows keyword... */
  4349.         if (isdigit(*s3)) {    /* Time - overwrite default time */
  4350.             strncpy(ybuf+8,s+i,DATEBUFLEN-8);
  4351.         } else {        /* Something else, keep default time */
  4352.             ckstrncat(ybuf," ",DATEBUFLEN); /* and append */
  4353.             ckstrncat(ybuf,s3,DATEBUFLEN); /* whatever we have */
  4354.         }
  4355.         }
  4356.     }
  4357.     s = ybuf;            /* Point to rewritten date-time */
  4358.     len = strlen(s);        /* Update length */
  4359.     isletter = 0;            /* Cancel this */
  4360.     }
  4361.  
  4362. /* Regular free-format non-symbolic date */
  4363.  
  4364.   normal:
  4365.  
  4366.     debug(F111,"cmcvtdate NORMAL",s,len);
  4367.     debug(F111,"cmcvtdate dow",s,dow);
  4368.     if (yyyymmdd[0] && !year) {
  4369.     ckstrncpy(yearbuf,yyyymmdd,5);
  4370.     ckstrncpy(monbuf,&yyyymmdd[4],3);
  4371.     ckstrncpy(daybuf,&yyyymmdd[6],3);
  4372.     year = yearbuf;
  4373.     month = monbuf;
  4374.     day = daybuf;
  4375.     nday = atoi(daybuf);
  4376.     }
  4377.     if (isdigit(s[0])) {        /* Time without date? */
  4378.     p = s;
  4379.     if (s[1] == ':') {
  4380.         debug(F111,"cmcvtdate NORMAL X1",s,len);
  4381.         goto dotime;
  4382.     } else if (len > 1 && isdigit(s[1]) && s[2] == ':') {
  4383.         debug(F111,"cmcvtdate NORMAL X2",s,len);
  4384.         goto dotime;
  4385.     } else if (rdigits(s) && len < 8) {
  4386.         debug(F111,"cmcvtdate NORMAL X3",s,len);
  4387.         goto dotime;
  4388.     }
  4389.     }
  4390.     if (len >= 8 && isdigit(*s)) {    /* Check first for yyyymmdd* */
  4391.     debug(F111,"cmcvtdate NORMAL A",s,len);
  4392.     cc = s[8];
  4393.     s[8] = NUL;            /* Isolate first 8 characters */
  4394.     if (rdigits(s)) {
  4395.         /* Have valid time separator? */
  4396.         p2 = cc ? ckstrchr(" Tt_-:",cc) : NULL;
  4397.         if (!cc || p2) {
  4398.         ckstrncpy(yyyymmdd,s,YYYYMMDD);    /* Valid separator */
  4399.         year = NULL;
  4400.         s += 8;                    /* or time not given */
  4401.         if (cc) s++;                /* Keep date */
  4402.         p = s;                    /* and go handle time */
  4403.         goto dotime;
  4404.         } else if (!p2) {
  4405.         if (isdigit(cc))
  4406.           makestr(&cmdatemsg,"Numeric date too long");
  4407.         else
  4408.           makestr(&cmdatemsg,"Invalid date-time separator");
  4409.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4410.         return(NULL);
  4411.         }
  4412.     }
  4413.     s[8] = cc;            /* Put this back! */
  4414.     }
  4415.     debug(F111,"cmcvtdate NORMAL non-yyyymmdd",s,len);
  4416.  
  4417.     /* Free-format date -- figure it out */
  4418.  
  4419. #ifdef COMMENT
  4420.     if (*s && !isdigit(*s)) {
  4421.     makestr(&cmdatemsg,"Unrecognized word in date");
  4422.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4423.     return(NULL);
  4424.     }
  4425. #endif /* COMMENT */
  4426.     for (i = 0; i < 8; i++)        /* Field types */
  4427.       ft[i] = -1;
  4428.     fld[i = 0] = (p = s);        /* First field */
  4429.     while (*p) {            /* Get next two fields */
  4430.     if (isdatesep(*p)) {        /* Have a date separator */
  4431.         if (i == 0) {
  4432.         datesep = *p;
  4433.         } else if (i == 1 && *p != datesep) {
  4434.         makestr(&cmdatemsg,"Inconsistent date separators");
  4435.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4436.         return(NULL);
  4437.         }
  4438.         *p++ = NUL;            /* Replace by NUL */
  4439.         if (*p) {            /* Now we're at the next field */
  4440.         while (*p == SP) p++;    /* Skip leading spaces */
  4441.         if (!*p) break;        /* Make sure we still have something */
  4442.         if (i == 2)        /* Last one? */
  4443.           break;
  4444.         fld[++i] = p;        /* No, record pointer to this one */
  4445.         } else {
  4446.         break;
  4447.         }        
  4448.     } else if ((*p == 'T' || *p == 't') && isdigit(*(p+1))) { /* Time */
  4449.         *p++ = NUL;
  4450.         break;
  4451.     } else if (*p == ':') {
  4452.         if (i == 0 && p == s) {
  4453.         nodate = 1;
  4454.         break;
  4455.         } else if (i != 0) {    /* After a date */
  4456.         if (i == 2) {        /* OK as date-time separator (VMS) */
  4457.             *p++ = NUL;
  4458.             break;
  4459.         }
  4460.         if (i < 2)
  4461.           makestr(&cmdatemsg,"Too few fields in date");
  4462.         else
  4463.           makestr(&cmdatemsg,"Misplaced time separator");
  4464.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4465.         return(NULL);
  4466.         }
  4467.         nodate = 1;            /* Or without a date */
  4468.         break;
  4469.     }
  4470.     p++;
  4471.     }
  4472.     if (p > s && i == 0)        /* Make sure we have a date */
  4473.       nodate = 1;            /* No date. */
  4474.  
  4475.     if (nodate && dow > -1) {        /* Have implied date from DOW? */
  4476.     goto dotime;            /* Use, use that, go do time. */
  4477.  
  4478.     } else if (nodate) {        /* No date and no implied date */
  4479.     char *tmp = NULL;        /* Substitute today's date */
  4480.     ztime(&tmp);
  4481.     if (!tmp)
  4482.       tmp  = "";
  4483.     if (!*tmp) {
  4484.         makestr(&cmdatemsg,"Problem supplying current date");
  4485.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4486.         return(NULL);
  4487.     }
  4488.     ckstrncpy(dbuf,tmp,26);        /* Reformat */
  4489.     if (dbuf[8] == SP) dbuf[8] = '0';
  4490.     fld[0] = dbuf+8;        /* dd */
  4491.     dbuf[10] = NUL;
  4492.     fld[1] = dbuf+4;        /* mmm */
  4493.     dbuf[7] = NUL;
  4494.     fld[2] = dbuf+20;        /* yyyy */
  4495.     dbuf[24] = NUL;
  4496.     hh = atoi(&dbuf[11]);
  4497.     mm = atoi(&dbuf[14]);
  4498.     ss = atoi(&dbuf[17]);
  4499.     p = s;                /* Back up source pointer to reparse */
  4500.     } else if (i < 2) {
  4501.     makestr(&cmdatemsg,"Too few fields in date");
  4502.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4503.     return(NULL);
  4504.     }
  4505.     /* Have three date fields - see what they are */
  4506.  
  4507.     for (k = 0, j = 0; j < 3; j++) {    /* Get number of non-numeric fields */
  4508.     ft[j] = rdigits(fld[j]);
  4509.     debug(F111,"cmcvtdate fld",fld[j],j);
  4510.     if (ft[j] == 0)
  4511.       k++;
  4512.     }
  4513.     kn = k;                /* How many numeric fields */
  4514.     month = NULL;            /* Strike out default values */
  4515.     year = NULL;
  4516.     day = NULL;
  4517.  
  4518.     if (k == 2 && ft[2] > 0) {        /* Jul 20, 2001 */
  4519.     int xx;
  4520.     xx = strlen(fld[1]);
  4521.     p3 = fld[1];
  4522.     if (xx > 0) if (p3[xx-1] == ',') {
  4523.         p3[xx-1] = NUL;
  4524.         if (rdigits(p3)) {
  4525.         k = 1;    
  4526.         ft[1] = 1;
  4527.         } else p3[xx-1] = ',';
  4528.     }
  4529.     }
  4530.     if (k > 1) {            /* We can have only one non-numeric */
  4531.     if (nodate)
  4532.       makestr(&cmdatemsg,"Unrecognized word in date"); 
  4533.     else if (!ft[2] && isdigit(*(fld[2])))
  4534.       makestr(&cmdatemsg,"Invalid date-time separator"); 
  4535.     else
  4536.       makestr(&cmdatemsg,"Too many non-numeric fields in date");
  4537.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4538.     return(NULL);
  4539.     }
  4540.     if (!ft[0]) {
  4541.     k = 0;
  4542.     } else if (!ft[1]) {
  4543.     k = 1;
  4544.     } else if (!ft[2]) {
  4545.     makestr(&cmdatemsg,"Non-digit in third date field");
  4546.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4547.     return(NULL);
  4548.     } else
  4549.       k = -1;
  4550.  
  4551.     if (k > -1) {
  4552.     if ((x = lookup(cmonths,fld[k],12,NULL)) < 0) {
  4553.         makestr(&cmdatemsg,"Unknown month");
  4554.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4555.         return(NULL);
  4556.     }
  4557.     sprintf(tmpbuf,"%02d",x);
  4558.     month = tmpbuf;
  4559.     }
  4560.     f2len = strlen(fld[2]);        /* Length of 3rd field */
  4561.  
  4562.     if (k == 0) {            /* monthname dd, yyyy */
  4563.     day = fld[1];
  4564.     year = fld[2];
  4565.     } else if (((int)strlen(fld[0]) == 4)) { /* yyyy-xx-dd */
  4566.     year = fld[0];
  4567.     day = fld[2];
  4568.     if (!month)
  4569.       month = fld[1];        /* yyyy-mm-dd */
  4570.     } else if (f2len == 4) {        /* xx-xx-yyyy */
  4571.     year = fld[2];
  4572.     if (month) {            /* dd-name-yyyy */
  4573.         day = fld[0];
  4574.     } else {            /* xx-xx-yyyy */
  4575.         int f0, f1;
  4576.         f0 = atoi(fld[0]);
  4577.         f1 = atoi(fld[1]);
  4578.         if (((f0 > 12) && (f1 <= 12)) || (f1 <= 12 && f0 == f1)) {
  4579.         day = fld[0];        /* mm-dd-yyyy */
  4580.         month = fld[1];
  4581.         } else if ((f0 <= 12) && (f1 > 12)) {
  4582.         if (!rdigits(fld[1])) {
  4583.             makestr(&cmdatemsg,"Day not numeric");
  4584.             debug(F111,"cmcvtdate",cmdatemsg,-1);
  4585.             return(NULL);
  4586.         } else {
  4587.             day = fld[1];    /* dd-mm-yyyy */
  4588.         }
  4589.         month = fld[0];
  4590.         } else {
  4591.         if (!f0 || !f1)
  4592.           makestr(&cmdatemsg,"Day or month out of range");
  4593.         else
  4594.           makestr(&cmdatemsg,"Day and month are ambiguous");
  4595.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4596.         return(NULL);
  4597.         }
  4598.     }
  4599.     } else if ((f2len < 4) &&        /* dd mmm yy (RFC822) */
  4600.            !rdigits(fld[1]) &&    /* middle field is monthname */
  4601.            rdigits(fld[2])) {
  4602.     int tmpyear;
  4603.     day = fld[0];
  4604.     if (!fld[2][1]) {
  4605.         makestr(&cmdatemsg,"Too few digits in year");
  4606.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4607.         return(NULL);
  4608.     }
  4609.     tmpyear = atoi(fld[2]);
  4610.     if (tmpyear < 50)        /* RFC 2822 windowing */
  4611.       tmpyear += 2000;
  4612.     else                /* This includes 3-digit years. */
  4613.       tmpyear += 1900;
  4614.     year = ckitoa(tmpyear);
  4615.  
  4616.     } else if ((f2len < 4) && (k < 0) && ((int)strlen(fld[0]) < 4)) {
  4617.     makestr(&cmdatemsg,"Ambiguous numeric date");
  4618.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4619.     return(NULL);
  4620.     } else if ((f2len > 4) && ft[2]) {
  4621.     makestr(&cmdatemsg,"Too many digits in year");
  4622.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4623.     return(NULL);
  4624.     } else {
  4625.     makestr(&cmdatemsg,"Unexpected date format");
  4626.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4627.     return(NULL);
  4628.     }
  4629.     x = atoi(month);
  4630.     sprintf(tmpbuf,"%02d",x);        /* 2-digit numeric month */
  4631.  
  4632. /*
  4633.    state = 1 = hours
  4634.    state = 2 = minutes
  4635.    state = 3 = seconds
  4636.    state = 4 = fractions of seconds
  4637. */
  4638.  
  4639.   dotime:
  4640.     if (isletter && (s == p)) {
  4641.     makestr(&cmdatemsg,"Unknown date-time word");
  4642.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4643.     return(NULL);
  4644.     }
  4645.     if (!year && yyyymmdd[0]) {
  4646.     debug(F110,"cmcvtdate dotime yyyymmdd",yyyymmdd,0);
  4647.     for (i = 0; i < 4; i++)
  4648.       yearbuf[i] = yyyymmdd[i];
  4649.     yearbuf[4] = NUL;
  4650.     monbuf[0] = yyyymmdd[4];
  4651.     monbuf[1] = yyyymmdd[5];
  4652.     monbuf[2] = NUL;
  4653.     daybuf[0] = yyyymmdd[6];
  4654.     daybuf[1] = yyyymmdd[7];
  4655.     daybuf[2] = NUL;
  4656.     day = daybuf;
  4657.     nday = atoi(daybuf);
  4658.     month = monbuf;
  4659.     year = yearbuf;
  4660.     }
  4661.     if (!year) {
  4662.     makestr(&cmdatemsg,"Internal error - date not defaulted");
  4663.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4664.     return(NULL);
  4665.     }
  4666.     /* Get here with day, month, and year set */
  4667.     debug(F110,"cmcvtdate dotime day",day,0);
  4668.     debug(F110,"cmcvtdate dotime month",month,0);
  4669.     debug(F110,"cmcvtdate dotime year",year,0);
  4670.     debug(F110,"cmcvtdate dotime s",s,0);
  4671.     debug(F110,"cmcvtdate dotime p",p,0);
  4672.     x = atoi(month);
  4673.     if (x > 12 || x < 1) {
  4674.     makestr(&cmdatemsg,"Month out of range");
  4675.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4676.     return(NULL);
  4677.     }
  4678.     nday  = atoi(day);
  4679.     i = mdays[x];
  4680.     if (x == 2) if (isleap(atoi(year))) i++;
  4681.     if (nday > i || nday < 1) {
  4682.     makestr(&cmdatemsg,"Day out of range");
  4683.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4684.     return(NULL);
  4685.     }
  4686.     if (!*p && t == 0) {
  4687.     sprintf(zbuf,"%04d%02d%02d",atoi(year),atoi(month),nday);    
  4688.     dp = zbuf;
  4689.     goto xcvtdate;
  4690.     }
  4691.     if (*p == '+' || *p == '-') {    /* GMT offset without a time */
  4692.     hh = 0;                /* so default time to 00:00:00 */
  4693.     mm = 0;
  4694.     ss = 0;
  4695.     goto cmtimezone;        /* and go do timezone */
  4696.     }
  4697.     if (*p && !isdigit(*p) && *p != ':') {
  4698.     makestr(&cmdatemsg,"Invalid time");
  4699.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4700.     return(NULL);
  4701.     }
  4702.     sprintf(yyyymmdd,"%s%s%02d",year,month,nday); /* for tz calculations... */
  4703.  
  4704.     state = 1;                /* Initialize time-parsing FSA */
  4705.     hh = 0;                /* hours */
  4706.     mm = 0;                /* minutes */
  4707.     ss = 0;                /* seconds */
  4708.     ff = -1;                /* fraction */
  4709.     d = 0;                /* Digit counter */
  4710.     p2 = p;                /* Preliminary digit count... */
  4711.     while (isdigit(*p2)) {
  4712.     d++;
  4713.     p2++;
  4714.     }
  4715.     if (d > 6) {
  4716.     makestr(&cmdatemsg,"Too many time digits");
  4717.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  4718.     return(NULL);
  4719.     }
  4720.     d = (d & 1 && *p2 != ':') ? 1 : 0;    /* Odd implies leading '0' */
  4721.  
  4722.     while (*p) {            /* Get the time, if any */
  4723.     if (isdigit(*p)) {        /* digit */
  4724.         if (d++ > 1) {
  4725.         state++;
  4726.         d = 1;
  4727.         }
  4728.         switch (state) {
  4729.           case 1:            /* Hours */
  4730.         hh = hh * 10 + (*p - '0');
  4731.         break;
  4732.           case 2:            /* Minutes */
  4733.         mm = mm * 10 + (*p - '0');
  4734.         break;
  4735.           case 3:            /* Seconds */
  4736.         ss = ss * 10 + (*p - '0');
  4737.         break;
  4738.           case 4:            /* Fraction of second */
  4739.         if (ff < 0)
  4740.           ff = (*p > '4') ? 1 : 0;
  4741.         break;
  4742.         }
  4743.     } else if (*p == ':') {        /* Colon */
  4744.         state++;
  4745.         d = 0;
  4746.         if (state > 3) {
  4747.         makestr(&cmdatemsg,"Too many time fields");
  4748.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4749.         return(NULL);
  4750.         }
  4751.     } else if (*p == '.') {
  4752.         if (state == 3) {
  4753.         state = 4;
  4754.         d = 0;
  4755.         } else {
  4756.         makestr(&cmdatemsg,"Improper fraction");
  4757.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4758.         return(NULL);
  4759.         }
  4760.     } else if (*p == SP) {        /* Space */
  4761.         while (*p && (*p == SP))    /* position to first nonspace */
  4762.           p++;
  4763.         break;
  4764.     } else if (isalpha(*p)) {    /* AM/PM/Z or timezone */
  4765.         break;
  4766.     } else if (*p == '+' || *p == '-') { /* GMT offset */
  4767.         break;
  4768.     } else {
  4769.         makestr(&cmdatemsg,"Invalid time characters");
  4770.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4771.         return(NULL);
  4772.     }
  4773.     p++;
  4774.     }
  4775.     if (!*p)                /* If nothing left */
  4776.       goto xcmdate;            /* go finish up */
  4777.  
  4778.     /* At this point we have HH, MM, SS, and FF */
  4779.     /* Now handle the rest: AM, PM, and/or timezone info */
  4780.  
  4781.     if (!ckstrcmp(p,"am",2,0)) {    /* AM/PM... */
  4782.     pmflag = 0;
  4783.     p += 2;
  4784.     } else if (!ckstrcmp(p,"a.m.",4,0)) {
  4785.     pmflag = 0;
  4786.     p += 4;
  4787.     } else if (!ckstrcmp(p,"pm",2,0)) {
  4788.     pmflag = 1;
  4789.     p += 2;
  4790.     } else if (!ckstrcmp(p,"p.m.",4,0)) {
  4791.     pmflag = 1;
  4792.     p += 4;
  4793.     }
  4794.     if (pmflag && hh < 12)        /* If PM was given */
  4795.       hh += 12;                /* add 12 to the hour */
  4796.  
  4797.     /* Now handle timezone */
  4798.  
  4799.   cmtimezone:
  4800.     debug(F110,"cmcvtdate timezone",p,0);
  4801.  
  4802.     zhh = 0;                /* GMT offset HH */
  4803.     zmm = 0;                /* GMT offset MM */
  4804.     gmtsign = 0;            /* Sign of GMT offset */
  4805.     isgmt = 0;                /* 1 if time is GMT */
  4806.  
  4807.     while (*p && *p == SP)        /* Gobble spaces */
  4808.       p++;
  4809.     if (!*p)                /* If nothing left */
  4810.       goto xcmdate;            /* we're done */
  4811.  
  4812.     if (isalpha(*p)) {            /* Something left */
  4813.     int zone = 0;            /* Alphabetic must be timezone */
  4814.     p2 = p;                /* Isolate timezone */
  4815.     p++;
  4816.     while (isalpha(*p))
  4817.       p++;
  4818.     p3 = p;
  4819.     cc = *p;
  4820.     *p = NUL;
  4821.     p = p2;                /* Have timezone, look it up */
  4822.     zone = lookup(usatz,p,nusatz,NULL);
  4823.     debug(F111,"cmcvtdate timezone alpha",p,zone);
  4824.  
  4825.     if (zone < 0) {            /* Not found */
  4826.         makestr(&cmdatemsg,"Unknown timezone");
  4827.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  4828.         return(NULL);
  4829.     }
  4830.     isgmt++;            /* All dates are GMT from here down */
  4831.     if (zone != 0) {        /* But not this one so make it GMT */
  4832.         hh += zone;            /* RFC 822 timezone: EST etc */
  4833.         debug(F101,"cmcvtdate hh + zone","",hh);
  4834.         if (hh > 23) {        /* Offset crosses date boundary */
  4835.         int i;
  4836.         long jd;
  4837.         jd = mjd(yyyymmdd);    /* Get MJD */
  4838.         jd += hh / 24;        /* Add new day(s) */
  4839.         hh = hh % 24;        /* and convert back to yyyymmdd */
  4840.         ckstrncpy(yyyymmdd,mjd2date(jd),YYYYMMDD);
  4841.         debug(F111,"cmcvtdate zone-adjusted date",yyyymmdd,hh);
  4842.         for (i = 0; i < 4; i++)
  4843.           yearbuf[i] = yyyymmdd[i];
  4844.         yearbuf[4] = NUL;
  4845.         monbuf[0] = yyyymmdd[4];
  4846.         monbuf[1] = yyyymmdd[5];
  4847.         monbuf[2] = NUL;
  4848.         daybuf[0] = yyyymmdd[6];
  4849.         daybuf[1] = yyyymmdd[7];
  4850.         daybuf[2] = NUL;
  4851.         day = daybuf;
  4852.         nday = atoi(daybuf);
  4853.         month = monbuf;
  4854.         year = yearbuf;
  4855.         }
  4856.     }
  4857.     p = p3;                /* Put back whatever we poked above */
  4858.     *p = cc;
  4859.  
  4860.     } else if (*p == '+' || *p == '-') { /* GMT/UTC offset */
  4861.     p3 = p;
  4862.     debug(F110,"cmcvtdate timezone GMT offset",p,0);
  4863.     gmtsign = (*p == '+') ? -1 : 1;
  4864.     isgmt++;
  4865.     p++;
  4866.     while (*p == SP) p++;
  4867.     d = 0;
  4868.     p2 = p;
  4869.     while (isdigit(*p)) {        /* Count digits */
  4870.         d++;
  4871.         p++;
  4872.     }
  4873.     if (d != 4) {            /* Strict RFC [2]822 */
  4874.         isgmt = 0;            /* If not exactly 4 digits */
  4875.         p = p3;            /* it's not a GMT offset. */
  4876.         goto delta;            /* So treat it as a delta time. */
  4877.     }
  4878.     d = (d & 1 && *p != ':') ? 1 : 0; /* Odd implies leading '0' */
  4879.     p = p2;
  4880.     debug(F111,"cmcvtdate GMT offset sign",p,gmtsign);
  4881.     debug(F101,"cmcvtdate GMT offset d","",d);
  4882.     state = 1;
  4883.     while (*p) {
  4884.         if (isdigit(*p)) {        /* digit */
  4885.         if (d++ > 1) {
  4886.             state++;
  4887.             d = 1;
  4888.         }
  4889.         switch (state) {
  4890.           case 1:
  4891.             zhh = zhh * 10 + (*p - '0');
  4892.             break;
  4893.           case 2:
  4894.             zmm = zmm * 10 + (*p - '0');
  4895.             break;
  4896.           default:        /* Ignore seconds or fractions */
  4897.             break;
  4898.         }            
  4899.         } else if (*p == ':') {    /* Colon */
  4900.         state++;
  4901.         d = 0;
  4902.         } else if (*p == SP || *p == '(') {
  4903.         break;
  4904.         } else {
  4905.         p = p3;            /* Maybe it's not a GMT offset. */
  4906.         goto delta;        /* So treat it as a delta time. */
  4907.         }
  4908.         p++;
  4909.     }
  4910.     }
  4911.     debug(F110,"cmcvtdate source string after timezone",p,0);
  4912.  
  4913.     if (*p) {                /* Anything left? */
  4914.     p2 = p;
  4915.     while (*p2 == SP)        /* Skip past spaces */
  4916.       p2++;
  4917.     if (*p2 == '(') {        /* RFC-822 comment? */
  4918.         int pc = 1;            /* paren counter */
  4919.         p2++;
  4920.         while (*p2) {
  4921.         if (*p2 == ')') {
  4922.             if (--pc == 0) {
  4923.             p2++;
  4924.             break;
  4925.             }
  4926.         } else if (*p2 == ')') {
  4927.             pc++;
  4928.         }
  4929.         p2++;
  4930.         }        
  4931.         while (*p2 == SP)        /* Skip past spaces */
  4932.           p2++;
  4933.         if (!*p2)            /* Anything left? */
  4934.           *p = NUL;            /* No, erase comment */
  4935.     }
  4936.     if (!*p2)            /* Anything left? */
  4937.       goto xcmdate;            /* No, done. */
  4938.     p = p2;
  4939.  
  4940.       delta:
  4941.     debug(F110,"cmcvtdate delta yyyymmdd",yyyymmdd,0);
  4942.     debug(F110,"cmcvtdate delta year",year,0);
  4943.     debug(F110,"cmcvtdate delta p",p,0);
  4944.  
  4945.     if (*p == '+' || *p == '-') {    /* Delta time */
  4946.         int state = NEED_DAYS;    /* Start off looking for days */
  4947.         char c = 0;
  4948.         dsign = 1;            /* Get sign */
  4949.         if (*p++ == '-')
  4950.           dsign = -1;
  4951.         while (*p == SP)        /* Skip intervening spaces */
  4952.           p++;
  4953.         while (state) {        /* FSA to parse delta time */
  4954.         if (state < 0 || !isdigit(*p)) {
  4955.             makestr(&cmdatemsg,"Invalid delta time");
  4956.             debug(F111,"cmcvtdate",cmdatemsg,-1);
  4957.             return(NULL);
  4958.         }
  4959.         p2 = p;            /* Get next numeric field */
  4960.         while (isdigit(*p2))
  4961.           p2++;
  4962.         c = *p2;        /* And break character */
  4963.         *p2 = NUL;        /* Terminate the number */
  4964.  
  4965.         switch (state) {    /* Interpret according to state */
  4966.           case NEED_DAYS:    /* Initial */
  4967.             if ((c == '-') ||    /* VMS format */
  4968.             ((c == 'd' || c == 'D')
  4969.              && !isalpha(*(p2+1)))) { /* Days */
  4970.             ddays = atoi(p);
  4971.             if (!*(p2+1))            
  4972.               state = 0;
  4973.             else              /* if anything is left */
  4974.               state = NEED_HRS;   /* now we want hours. */
  4975.             } else if ((c == 'W' || c == 'w') && !isalpha(*(p2+1))) {
  4976.             ddays = atoi(p) * 7;   /* weeks... */
  4977.             if (!*(p2+1))            
  4978.               state = 0;
  4979.             else
  4980.               state = NEED_HRS;
  4981.             } else if ((c == 'M' || c == 'm') && !isalpha(*(p2+1))) {
  4982.             dmonths = atoi(p); /* months... */
  4983.             if (!*(p2+1))            
  4984.               state = 0;
  4985.             else
  4986.               state = NEED_HRS;
  4987.             } else if ((c == 'Y' || c == 'y') && !isalpha(*(p2+1))) {
  4988.             dyears = atoi(p); /* years... */
  4989.             if (!*(p2+1))            
  4990.               state = 0;
  4991.             else
  4992.               state = NEED_HRS;
  4993.             } else if (c == ':') { /* delimiter is colon */
  4994.             dhours = atoi(p);  /* so it's hours */
  4995.             state = NEED_MINS; /* now we want minutes */
  4996.             } else if (!c) {       /* end of string */
  4997.             dhours = atoi(p);  /* it's still hours */
  4998.             state = 0;         /* and we're done */
  4999.             } else if (isalpha(c) || c == SP) {
  5000.             if (c == SP) {    /* It's a keyword? */
  5001.                 p2++;    /* Skip spaces */
  5002.                 while (*p2 == SP)
  5003.                   p2++;
  5004.             } else {    /* or replace first letter */
  5005.                 *p2 = c;
  5006.             }
  5007.             p3 = p2;    /* p2 points to beginning of keyword */
  5008.             while (isalpha(*p3)) /* Find end of keyword */
  5009.               p3++;
  5010.             c = *p3;    /* NUL it out so we can look it up */
  5011.             if (*p3)    /* p3 points to keyword terminator */
  5012.               *p3 = NUL;
  5013.             units = lookup(timeunits,p2,nunits,NULL);
  5014.             if (units < 0) {
  5015.                 makestr(&cmdatemsg,"Invalid units in delta time");
  5016.                 debug(F111,"cmcvtdate",cmdatemsg,-1);
  5017.                 return(NULL);
  5018.             }
  5019.             *p2 = NUL;    /* Re-terminate the number */
  5020.             *p3 = c;
  5021.             while (*p3 == SP) /* Point at field after units */
  5022.               p3++;
  5023.             p2 = p3;
  5024.             switch (units) {
  5025.               case TU_DAYS:
  5026.                 ddays = atoi(p);
  5027.                 break;
  5028.               case TU_WEEKS:
  5029.                 ddays = atoi(p) * 7;
  5030.                 break;
  5031.               case TU_MONTHS:
  5032.                 dmonths = atoi(p);
  5033.                 break;
  5034.               case TU_YEARS:
  5035.                 dyears = atoi(p);
  5036.                 break;
  5037.             }
  5038.             if (*p2) {
  5039.                 state = NEED_HRS;
  5040.                 p2--;
  5041.             } else
  5042.               state = 0;
  5043.  
  5044.             } else {        /* Anything else */
  5045.             state = -1;    /* is an error */
  5046.             }
  5047.             break;
  5048.           case NEED_HRS:    /* Looking for hours */
  5049.             debug(F000,"cmcvtdate NEED_HRS",p,c);
  5050.             if (c == ':') {
  5051.             dhours = atoi(p);
  5052.             state = NEED_MINS;
  5053.             } else if (!c) {
  5054.             dhours = atoi(p);
  5055.             state = 0;
  5056.             } else {
  5057.             state = -1;
  5058.             }
  5059.             break;
  5060.           case NEED_MINS:    /* Looking for minutes */
  5061.             if (c == ':') {
  5062.             dmins = atoi(p);
  5063.             state = NEED_SECS;
  5064.             } else if (!c) {
  5065.             dmins = atoi(p);
  5066.             state = 0;
  5067.             } else {
  5068.             state = -1;
  5069.             }
  5070.             break;
  5071.           case NEED_SECS:    /* Looking for seconds */
  5072.             if (c == '.') {
  5073.             dsecs = atoi(p);
  5074.             state = NEED_FRAC;
  5075.             } else if (!c) {
  5076.             dsecs = atoi(p);
  5077.             state = 0;
  5078.             } else {
  5079.             state = -1;
  5080.             }
  5081.             break;
  5082.           case NEED_FRAC:    /* Fraction of second */
  5083.             if (!c && rdigits(p)) {
  5084.             if (*p > '4')
  5085.               dsecs++;
  5086.             state = 0;
  5087.             } else {
  5088.             state = -1;
  5089.             }
  5090.             break;
  5091.         }
  5092.         if (c)            /* next field if any */
  5093.           p = p2 + 1;
  5094.         }
  5095.         havedelta = 1;
  5096.  
  5097.     } else {
  5098.         makestr(&cmdatemsg,"Extraneous material at end");
  5099.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  5100.         return(NULL);
  5101.     }
  5102.     }
  5103.  
  5104.  xcmdate:
  5105.  
  5106.     if ((t != 2 && hh > 24) || hh < 0) { /* Hour range check */
  5107.     makestr(&cmdatemsg,"Invalid hours");
  5108.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  5109.     return(NULL);
  5110.     }
  5111.     if (mm > 59) {            /* Minute range check */
  5112.     makestr(&cmdatemsg,"Invalid minutes");
  5113.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  5114.     return(NULL);
  5115.     }
  5116.     if (ff > 0) {            /* Fraction of second? */
  5117.     if (ss < 59) {
  5118.         ss++;
  5119.         ff = 0;
  5120.     } else if (mm < 59) {
  5121.         ss = 0;
  5122.         mm++;
  5123.         ff = 0;
  5124.     } else if (hh < 24) {
  5125.         ss = 0;
  5126.         mm = 0;
  5127.         hh++;
  5128.         ff = 0;
  5129.     }
  5130.     /* Must add a day -- leave ff at 1... */
  5131.     /* (DO SOMETHING ABOUT THIS LATER) */
  5132.     }
  5133.     if (ss > 60) {            /* Seconds range check */
  5134.     makestr(&cmdatemsg,"Invalid seconds"); /* 60 is ok because of */
  5135.     debug(F111,"cmcvtdate",cmdatemsg,-1);  /* Leap Second. */
  5136.     return(NULL);
  5137.     }
  5138.     if ((mm < 0 || ss < 0) ||
  5139.     (t != 2 && (ss > 0 || mm > 0) && hh > 23)) {
  5140.     makestr(&cmdatemsg,"Invalid minutes or seconds");
  5141.     debug(F111,"cmcvtdate",cmdatemsg,-1);
  5142.     return(NULL);
  5143.     }
  5144.     debug(F110,"cmcvtdate year",year,0);
  5145.     debug(F110,"cmcvtdate month",month,0);
  5146.     debug(F101,"cmcvtdate nday","",nday);
  5147.     debug(F101,"cmcvtdate hh","",hh);
  5148.     debug(F101,"cmcvtdate mm","",mm);
  5149.     debug(F101,"cmcvtdate ss","",ss);
  5150.     debug(F101,"cmcvtdate gmtsign","",gmtsign);
  5151.     debug(F101,"cmcvtdate zhh","",zhh);
  5152.     debug(F101,"cmcvtdate zmm","",zmm);
  5153.     debug(F101,"cmcvtdate isgmt","",isgmt);
  5154.  
  5155. #ifdef ZLOCALTIME
  5156. /* Handle timezone -- first convert to GMT */
  5157.  
  5158.     zdd = 0;                /* Days changed */
  5159.     if (isgmt && (zmm || zhh)) {    /* If GMT offset given */
  5160.     long sec1, sec2, zz;
  5161.     sec1 = ss + 60 * mm + 3600 * hh;
  5162.     sec2 = gmtsign * (60 * zmm + 3600 * zhh);
  5163.     sec1 += sec2;
  5164.     if (sec1 < 0) {
  5165.         sec1 = 0 - sec1;
  5166.         zdd = 0L - (sec1 / 86400L);
  5167.         sec1 = sec1 % 86400L;
  5168.     } else if (sec1 > 86400L) {
  5169.         zdd = sec1 / 86400L;
  5170.         sec1 = sec1 % 86400L;
  5171.     }
  5172.     ss = sec1 % 60;
  5173.     zz = sec1 / 60;
  5174.     mm = zz % 60;
  5175.     hh = zz / 60;
  5176.     debug(F101,"cmcvtdate NEW hh","",hh);
  5177.     debug(F101,"cmcvtdate NEW mm","",mm);
  5178.     debug(F101,"cmcvtdate NEW dd","",zdd);
  5179.  
  5180. /* At this point hh:mm:ss is in GMT and zdd is the calendar adjustment */
  5181.  
  5182.     }
  5183. #endif /* ZLOCALTIME */
  5184.  
  5185.     if (yyyymmdd[0] && !year) {
  5186.     ckstrncpy(yearbuf,yyyymmdd,5);
  5187.     ckstrncpy(monbuf,&yyyymmdd[4],3);
  5188.     ckstrncpy(daybuf,&yyyymmdd[6],3);
  5189.     year = yearbuf;
  5190.     month = monbuf;
  5191.     day = daybuf;
  5192.     nday = atoi(daybuf);
  5193.     }
  5194.     sprintf(zbuf,"%04d%02d%02d %02d:%02d:%02d", /* SAFE */
  5195.         atoi(year),atoi(month),nday,hh,mm,ss
  5196.         );
  5197.     dp = zbuf;
  5198.  
  5199. #ifdef ZLOCALTIME
  5200.     /* Now convert from GMT to local time */
  5201.  
  5202.     if (isgmt) {            /* If GMT convert to local time */
  5203.     debug(F110,"cmcvtdate GMT 1",dp,0);
  5204.     if (zdd) {            /* Apply any calendar adjustment */
  5205.         long zz;
  5206.         zz = mjd(dp) + zdd;
  5207.         sprintf(zbuf,"%s %02d:%02d:%02d",mjd2date(zz),hh,mm,ss);
  5208.     }
  5209.     debug(F110,"cmcvtdate GMT 2",dp,0);
  5210.     if ((p = zlocaltime(dp))) {
  5211.         debug(F110,"cmcvtdate asctime zlocaltime",p,0);
  5212.         if (p) ckstrncpy(zbuf,p,18);
  5213.     }
  5214.     debug(F110,"cmcvtdate GMT 3",dp,0);
  5215.     for (i = 0; i < 4; i++)
  5216.       yearbuf[i] = dp[i];
  5217.     yearbuf[4] = NUL;
  5218.     monbuf[0] = dp[4];
  5219.     monbuf[1] = dp[5];
  5220.     monbuf[2] = NUL;
  5221.     daybuf[0] = dp[6];
  5222.     daybuf[1] = dp[7];
  5223.     daybuf[2] = NUL;
  5224.     day = daybuf;
  5225.     nday = atoi(daybuf);
  5226.     month = monbuf;
  5227.     year = yearbuf;
  5228.     hh = atoi(&dp[9]);
  5229.     mm = atoi(&dp[12]);
  5230.     ss = atoi(&dp[15]);
  5231.     }
  5232. #endif /* ZLOCALTIME */
  5233.  
  5234. #ifdef DEBUG
  5235.     if (deblog) {
  5236.     debug(F101,"cmcvtdate hour","",hh);
  5237.     debug(F101,"cmcvtdate minute","",mm);
  5238.     debug(F101,"cmcvtdate second","",ss);
  5239.     }
  5240. #endif /* DEBLOG */
  5241.  
  5242.     makestr(&cmdatemsg,NULL);
  5243.     if (havedelta) {
  5244. #ifdef DEBUG
  5245.     if (deblog) {
  5246.         debug(F110,"cmcvtdate base ",dp,0);
  5247.         debug(F101,"cmcvtdate delta sign","",dsign);
  5248.         debug(F101,"cmcvtdate delta yrs ","",dyears);
  5249.         debug(F101,"cmcvtdate delta mos ","",dmonths);
  5250.         debug(F101,"cmcvtdate delta days","",ddays);
  5251.         debug(F101,"cmcvtdate delta hrs ","",dhours);
  5252.         debug(F101,"cmcvtdate delta mins","",dmins);
  5253.         debug(F101,"cmcvtdate delta secs","",dsecs);
  5254.     }
  5255. #endif /* DEBLOG */
  5256.     if (!(dp = cmdelta(atoi(year),
  5257.             atoi(month),
  5258.             nday, hh, mm, ss,
  5259.             dsign, dyears, dmonths, ddays, dhours, dmins, dsecs))) {
  5260.         debug(F111,"cmcvtdate",cmdatemsg,-1);
  5261.         return(NULL);
  5262.     }
  5263.     }
  5264.  
  5265.   xcvtdate:                /* Exit point for success */
  5266.     {
  5267.     int len, k, n;
  5268.     char * p;
  5269.     debug(F110,"cmcvtdate xcvtdate dp",dp,0);
  5270.     if (!dp) dp = "";        /* Shouldn't happen */
  5271.     if (!*dp) return(NULL);        /* ... */
  5272.     len = strlen(dp);
  5273.     debug(F111,"cmcvtdate result",dp,len);
  5274.     k = cmdatebp - (char *)cmdatebuf; /* Space used */
  5275.     n = CMDATEBUF - k - 1;        /* Space left */
  5276.     if (n < len) {            /* Not enough? */
  5277.         cmdatebp = cmdatebuf;    /* Wrap around */
  5278.         n = CMDATEBUF;
  5279.     }
  5280.     ckstrncpy(cmdatebp,dp,n);
  5281.     p = cmdatebp;
  5282.     cmdatebp += len + 1;
  5283.     return(p);
  5284.     }
  5285. }
  5286.  
  5287. int
  5288. cmvdate(d) char * d; {            /* Verify date-time */
  5289.     int i;
  5290.     if (!d) return(0);
  5291.     if ((int)strlen(d) != 17) return(0);
  5292.     for (i = 0; i < 8; i++) { if (!isdigit(d[i])) return(0); }
  5293.     if (!isdigit(d[9])  || !isdigit(d[10]) ||
  5294.     !isdigit(d[12]) || !isdigit(d[13]) ||
  5295.     !isdigit(d[15]) || !isdigit(d[16]))
  5296.       return(0);
  5297.     if (!ckstrchr(" Tt_-:",d[8])) return(0);
  5298.     if (d[11] != ':' && d[14] != ':') return(0);
  5299.     return(1);
  5300. }
  5301.  
  5302. /* c m d i f f d a t e  --  Get difference between two date-times */
  5303.  
  5304. char *
  5305. cmdiffdate(d1,d2) char * d1, * d2; {
  5306.     char d1buf[9], d2buf[9];
  5307.     char x1buf[18], x2buf[18];
  5308.     char * p;
  5309.  
  5310.     int hh1 = 0, mm1 = 0, ss1 = 0;
  5311.     int hh2 = 0, mm2 = 0, ss2 = 0;
  5312.     int hh, mm, ss;
  5313.     int sign;
  5314.     long jd1, jd2, jd, f1, f2, fx;
  5315.     static char result[24], *rp;
  5316.  
  5317.     debug(F110,"cmdiffdate d1 A",d1,0);
  5318.     debug(F110,"cmdiffdate d2 A",d2,0);
  5319.  
  5320.     if (!(p = cmcvtdate(d1,1)))        /* Convert dates to standard format */
  5321.       return(NULL);
  5322.     ckstrncpy(x1buf,p,18);
  5323.     d1 = x1buf;
  5324.  
  5325.     if (!(p = cmcvtdate(d2,1)))
  5326.       return(NULL);
  5327.     ckstrncpy(x2buf,p,18);
  5328.     d2 = x2buf;
  5329.  
  5330.     debug(F110,"cmdiffdate d1 B",d1,0);
  5331.     debug(F110,"cmdiffdate d2 B",d2,0);
  5332.     if (!cmvdate(d1) || !cmvdate(d2))
  5333.       return(NULL);
  5334.  
  5335.     hh1 = atoi(&d1[9]);            /* Get hours, minutes, and seconds */
  5336.     mm1 = atoi(&d1[12]);        /* for first date */
  5337.     ss1 = atoi(&d1[15]);
  5338.     ckstrncpy(d1buf,d1,9);
  5339.  
  5340.     hh2 = atoi(&d2[9]);            /* ditto for second date */
  5341.     mm2 = atoi(&d2[12]);
  5342.     ss2 = atoi(&d2[15]);
  5343.     ckstrncpy(d2buf,d2,9);
  5344.     
  5345.     jd1 = mjd(d1buf);            /* Get the two Julian dates */
  5346.     jd2 = mjd(d2buf);
  5347.     f1 = ss1 + 60 * mm1 + 3600 * hh1;    /* Convert first time to seconds */
  5348.  
  5349.     f2 = ss2 + 60 * mm2 + 3600 * hh2;    /* Ditto for second time */
  5350.     debug(F101,"cmdiffdate jd1","",jd1);
  5351.     debug(F101,"cmdiffdate f1","",f1);
  5352.     debug(F101,"cmdiffdate jd2","",jd2);
  5353.     debug(F101,"cmdiffdate f2","",f2);
  5354.   
  5355.     if (jd2 > jd1 || (jd1 == jd2 && f2 > f1)) {
  5356.         sign = -1; 
  5357.         if (f1 > f2) {jd2--; f2 += 86400L;}
  5358.         jd = jd2 - jd1;
  5359.         fx = f2 - f1;
  5360.     } else {
  5361.         sign = 1;
  5362.         if (f2 > f1) {jd1--; f1 += 86400L;}
  5363.         jd = jd1 - jd2;
  5364.         fx = f1 - f2;
  5365.     }
  5366.     debug(F111,"cmdiffdate sign jd",sign<0?"-":"+",jd);
  5367.     debug(F101,"cmdiffdate fx","",fx);
  5368.   
  5369.     hh = (int) (fx / 3600L);        /* Convert seconds to hh:mm:ss */
  5370.  
  5371.     mm = (int) (fx % 3600L) / 60L;
  5372.     ss = (int) (fx % 3600L) % 60L;
  5373.  
  5374.     rp = result;            /* Format the result */
  5375.     *rp++ = (sign < 0) ? '-' : '+';
  5376.     if (jd != 0 && hh+mm+ss == 0) {
  5377.     sprintf(rp,"%ldd",jd);
  5378.     } else if (jd == 0) {
  5379.     if (ss == 0)
  5380.       sprintf(rp,"%d:%02d",hh,mm);
  5381.     else
  5382.       sprintf(rp,"%d:%02d:%02d",hh,mm,ss);
  5383.     } else {
  5384.     if (ss == 0)
  5385.       sprintf(rp,"%ldd%d:%02d",jd,hh,mm);
  5386.     else
  5387.       sprintf(rp,"%ldd%d:%02d:%02d",jd,hh,mm,ss);
  5388.     }
  5389.     debug(F110,"cmdiffdate result",result,0);
  5390.     return((char *)result);
  5391. }
  5392.  
  5393. #ifndef NOSPL
  5394. /* s h u f f l e d a t e  --  Rearrange date string */
  5395.  
  5396. /*
  5397.   Call with:
  5398.     A date string in standard format: yyyymmdd hh:mm:ss (time optional).
  5399.     Options:
  5400.       1: Reformat date to yyyy-mmm-dd (mmm = English month abbreviation).
  5401.       2: Reformat date to dd-mmm-yyyy (mmm = English month abbreviation).
  5402.       3: Reformat as numeric yyyymmddhhmmss.
  5403.       4: Reformat in asctime() format Sat Nov 26 11:10:34 2005
  5404.     Returns:
  5405.       Pointer to result if args valid, otherwise original arg pointer.
  5406. */
  5407. char *
  5408. shuffledate(p,opt) char * p; int opt; {
  5409.     extern char * wkdays[];
  5410.     int len;
  5411.     char ibuf[32];
  5412.     static char obuf[48];
  5413.     char c;
  5414.     int yy, dd, mm;
  5415.  
  5416.     if (!p) p = "";
  5417.     if (!*p) p = ckdate();
  5418.     if (opt < 1 || opt > 4)
  5419.       return(p);
  5420.     len = strlen(p);
  5421.     if (len < 8 || len > 31) return(p);
  5422.     if (opt == 4) {            /* Asctime format (26 Nov 2005) */
  5423.     char c, * s;
  5424.     long z; int k;
  5425.     ckstrncpy(ibuf,p,31);
  5426.     k = len;
  5427.     while (k >= 0 && ibuf[k] == CR || ibuf[k] == LF)
  5428.       ibuf[k--] = NUL;
  5429.     while (k >= 0 && ibuf[k] == SP || ibuf[k] == HT)
  5430.       ibuf[k--] = NUL;
  5431.     if (k < 9) ckstrncpy(&ibuf[8]," 00:00:00",9);
  5432.     p = ibuf;
  5433.         z = mjd(p);                     /* Convert to modified Julian date */
  5434.         z = z % 7L;
  5435.         if (z < 0) {
  5436.             z = 0 - z;
  5437.             k = 6 - ((int)z + 3) % 7;
  5438.         } else {
  5439.             k = ((int)z + 3) % 7;    /* Day of week */
  5440.         }
  5441.     s = wkdays[k];
  5442.         obuf[0] = s[0];            /* Day of week */
  5443.         obuf[1] = s[1];
  5444.         obuf[2] = s[2];
  5445.         obuf[3] = SP;            /* Space */
  5446.     c = p[6];
  5447.         p[6] = NUL;
  5448.     mm = atoi(&ibuf[4]);        /* Month */
  5449.     s = moname[mm-1];        /* Name of month */
  5450.     p[6] = c;
  5451.  
  5452.         obuf[4] = s[0];            /* Month */
  5453.         obuf[5] = s[1];
  5454.         obuf[6] = s[2];
  5455.         obuf[7] = SP;            /* Space */
  5456.     if (p[6] == '0')        /* Date of month */
  5457.       obuf[8] = SP;
  5458.     else
  5459.       obuf[8] = p[6];
  5460.         obuf[9] = p[7];
  5461.     ckstrncpy(&obuf[10],&p[8],10);    /* Time */
  5462.         obuf[19] = SP;            /* Space */
  5463.     obuf[20] = p[0];        /* Year */
  5464.     obuf[21] = p[1];
  5465.     obuf[22] = p[2];
  5466.     obuf[23] = p[3];
  5467.     obuf[24] = NUL;
  5468.     return((char *)obuf);
  5469.     }
  5470.     if (opt == 3) {
  5471.     ckstrncpy(obuf,p,48);
  5472.     /* yyyymmdd hh:mm:ss */
  5473.     /* 01234567890123456 */
  5474.     /* yyyymmddhhmmss    */
  5475.     obuf[8] = obuf[9];
  5476.     obuf[9] = obuf[10];
  5477.     obuf[10] = obuf[12];
  5478.     obuf[11] = obuf[13];
  5479.     obuf[12] = obuf[15];
  5480.     obuf[13] = obuf[16];
  5481.     obuf[14] = NUL;
  5482.     return((char *)obuf);
  5483.     }
  5484.     ckstrncpy(ibuf,p,32);
  5485.     c = ibuf[4];            /* Warning: not Y10K compliant */
  5486.     ibuf[4] = NUL;
  5487.     if (!rdigits(ibuf))
  5488.       return(p);
  5489.     yy = atoi(ibuf);
  5490.     if (yy < 1 || yy > 9999)
  5491.       return(p);
  5492.     ibuf[4] = c;
  5493.     c = ibuf[6];
  5494.     ibuf[6] = NUL;
  5495.     if (!rdigits(&ibuf[4]))
  5496.       return(p);
  5497.     mm = atoi(&ibuf[4]);
  5498.     if (mm < 1 || mm > 12)
  5499.       return(p);
  5500.     ibuf[6] = c;
  5501.     c = ibuf[8];
  5502.     ibuf[8] = NUL;
  5503.     if (!rdigits(&ibuf[6]))
  5504.       return(p);
  5505.     dd = atoi(&ibuf[6]);
  5506.     ibuf[8] = c;
  5507.     if (dd < 1 || mm > 31)
  5508.       return(p);
  5509.     /* IGNORE WARNINGS ABOUT moname[] REFS OUT OF RANGE - it's prechecked. */
  5510.     switch (opt) {
  5511.       case 1:
  5512.     sprintf(obuf,"%04d-%s-%02d%s",yy,moname[mm-1],dd,&ibuf[8]);
  5513.     break;
  5514.       case 2:
  5515.     sprintf(obuf,"%02d-%s-%04d%s",dd,moname[mm-1],yy,&ibuf[8]);
  5516.     }
  5517.     return((char *)obuf);
  5518. }
  5519. #endif    /* NOSPL */
  5520.  
  5521. /*  C K C V T D A T E  --  Like cmcvtdate(), but returns string.  */
  5522. /*  For use by date-related functions */
  5523. /*  See calling conventions for cmcvtdate() above. */
  5524.  
  5525. char *
  5526. ckcvtdate(p,t) char * p; int t; {
  5527.     char * s;
  5528.     if (!(s = cmcvtdate(p,t)))
  5529.       return("<BAD_DATE_OR_TIME>");    /* \fblah() error message */
  5530.     else
  5531.       return(s);
  5532. }
  5533.  
  5534.  
  5535. /*  C M D A T E  --  Parse a date and/or time  */
  5536.  
  5537. /*
  5538.   Accepts date in various formats.  If the date is recognized,
  5539.   this routine returns 0 or greater with the result string pointer
  5540.   pointing to a buffer containing the date as "yyyymmdd hh:mm:ss".
  5541. */
  5542. int
  5543. cmdate(xhlp,xdef,xp,quiet,f) char *xhlp, *xdef, **xp; int quiet; xx_strp f; {
  5544.     int x, rc;
  5545.     char *o, *s, *zq, *dp;
  5546.  
  5547.     cmfldflgs = 0;
  5548.     if (!xhlp) xhlp = "";
  5549.     if (!xdef) xdef = "";
  5550.     if (!*xhlp) xhlp = "Date and/or time";
  5551.     *xp = "";
  5552.  
  5553.     rc = cmfld(xhlp,xdef,&s,(xx_strp)0);
  5554.     debug(F101,"cmdate cmfld rc","",rc);
  5555.     if (rc < 0)
  5556.       return(rc);
  5557.     debug(F110,"cmdate 1",s,0);
  5558.     o = s;                /* Remember what they typed. */
  5559.     s = brstrip(s);
  5560.     debug(F110,"cmdate 2",s,0);
  5561.  
  5562.     x = 0;
  5563.     if (f) {                /* If a conversion function is given */
  5564.     char * pp;
  5565.     zq = atxbuf;            /* do the conversion. */
  5566.     pp = atxbuf;
  5567.     atxn = CMDBL;
  5568.     if ((x = (*f)(s,&zq,&atxn)) < 0) return(-2);
  5569.     if (!*pp)
  5570.       pp = xdef;
  5571.     if (setatm(pp,0) < 0) {
  5572.         if (!quiet) printf("?Evaluated date too long\n");
  5573.         return(-9);
  5574.     }
  5575.     s = atxbuf;
  5576.     }
  5577.     dp = cmcvtdate(s,1);
  5578.     if (!dp) {
  5579.     if (!quiet) printf("?%s\n",cmdatemsg);
  5580.     return(-9);
  5581.     }
  5582.     *xp = dp;
  5583.     return(0);
  5584. }
  5585.  
  5586. #ifdef CK_RECALL            /* Command-recall functions */
  5587.  
  5588. /*  C M R I N I  --  Initialize or change size of command recall buffer */
  5589.  
  5590. int
  5591. cmrini(n) int n; {
  5592.     int i;
  5593.     if (recall && in_recall) {        /* Free old storage, if any */
  5594.     for (i = 0; i < cm_recall; i++) {
  5595.         if (recall[i]) {
  5596.         free(recall[i]);
  5597.         recall[i] = NULL;
  5598.         }
  5599.     }
  5600.     free(recall);
  5601.     recall = NULL;
  5602.     }
  5603.     cm_recall = n;            /* Set new size */
  5604.     rlast = current = -1;        /* Initialize pointers */
  5605.     if (n > 0) {
  5606.     recall = (char **)malloc((cm_recall + 1) * sizeof(char *));
  5607.     if (!recall)
  5608.       return(1);
  5609.     for (i = 0; i < cm_recall; i++) {
  5610.         recall[i] = NULL;
  5611.     }
  5612.     in_recall = 1;            /* Recall buffers init'd */
  5613.     }
  5614.     return(0);
  5615. }
  5616.  
  5617. /*  C M A D D N E X T  --  Force addition of next command */
  5618.  
  5619. VOID
  5620. cmaddnext() {
  5621.     if (on_recall && in_recall) {    /* Even if it doesn't come */
  5622.     force_add = 1;            /* from the keyboard */
  5623.     newcmd = 1;
  5624.     no_recall = 0;
  5625.     }
  5626. }
  5627.  
  5628. /*  C M G E T C M D  --  Find most recent matching command  */
  5629.  
  5630. char *
  5631. cmgetcmd(s) char * s; {
  5632.     int i;
  5633.     for (i = current; i >= 0; i--) {    /* Search backward thru history list */
  5634.     if (!recall[i]) continue;    /* This one's null, skip it */
  5635.     if (ckmatch(s,recall[i],0,1))    /* Match? */
  5636.       return(recall[i]);        /* Yes, return pointer */
  5637.     }
  5638.     return(NULL);            /* No match, return NULL pointer */
  5639. }
  5640. #endif /* CK_RECALL */
  5641.  
  5642. /*  A D D C M D  --  Add a command to the recall buffer  */
  5643.  
  5644. VOID
  5645. addcmd(s) char * s; {
  5646.     int len = 0, nq = 0;
  5647.     char * p;
  5648. #ifdef CKLEARN
  5649.     extern int learning;
  5650. #endif /* CKLEARN */
  5651.  
  5652.     if (xcmdsrc)            /* Only for interactive commands */
  5653.       return;
  5654.  
  5655.     if (!newcmd)            /* The command has been here already */
  5656.       return;                /* so ignore it. */
  5657.     newcmd = 0;                /* It's new but do this only once. */
  5658.  
  5659.     if (!s) s = cmdbuf;
  5660.     if (s[0])
  5661.       len = strlen(s);
  5662.  
  5663.     if (len < 1)            /* Don't save empty commands */
  5664.       return;
  5665.  
  5666.     p = s;
  5667.     while (*p) { if (*p++ == '?') nq++; } /* Count question marks */
  5668.  
  5669. #ifdef CKLEARN
  5670.     if (learning)            /* If a learned script is active */
  5671.       learncmd(s);            /* record this command. */
  5672. #endif /* CKLEARN */
  5673.  
  5674.     debug(F010,"CMD(P)",s,0);        /* Maybe record it in the debug log */
  5675.  
  5676. #ifdef CKSYSLOG
  5677.     if (ckxlogging) {            /* Maybe record it in syslog */
  5678.     if (ckxsyslog >= SYSLG_CX || ckxsyslog >= SYSLG_CM)
  5679.       cksyslog(SYSLG_CX, 1, "command", s, NULL);
  5680.     }
  5681. #endif /* CKSYSLOG */
  5682.  
  5683. #ifdef CK_RECALL
  5684.     last_recall = 0;
  5685.  
  5686.     if (on_recall &&            /* Command recall is on? */
  5687.     cm_recall > 0 &&        /* Recall buffer size is > 0? */
  5688.     !no_recall) {            /* Not not saving this command? */
  5689.  
  5690.     if (!force_add && rlast > -1)    /* If previous command was identical */
  5691.       if (!strcmp(s,recall[rlast])) /* don't add another copy */
  5692.         return;
  5693.  
  5694.     force_add = 0;            /* Reset now in case it was set */
  5695.  
  5696.         if (rlast >= cm_recall - 1) {    /* Recall buffer full? */
  5697.         int i;
  5698.         if (recall[0]) {        /* Discard oldest command */
  5699.         free(recall[0]);
  5700.         recall[0] = NULL;
  5701.         }
  5702.         for (i = 0; i < rlast; i++) {  /* The rest */
  5703.         recall[i] = recall[i+1];   /* move back */
  5704.         }
  5705.         rlast--;            /* Now we have one less */
  5706.     }
  5707.         rlast++;            /* Index of last command in buffer */
  5708.     current = rlast;        /* Also now the current command */
  5709.     if (current >= cm_recall) {    /* Shouldn't happen */
  5710.         printf("?Command history error\n");    /* but if it does */
  5711.         on_recall = 0;                /* turn off command saving */
  5712. #ifdef COMMENT
  5713.     } else if (nq > 0) {        /* Have at least one question mark */
  5714.         recall[current] = malloc(len+nq+1);
  5715.         if (recall[current]) {
  5716.         p = recall[current];
  5717.         while (*s) {
  5718.             if (*s == '?')
  5719.               *p++ = '\\';
  5720.             *p++ = *s++;
  5721.         }
  5722.         *p = NUL;
  5723.         }
  5724. #endif /* COMMENT */
  5725.     } else {            /* Normal case, just copy */
  5726.         recall[current] = malloc(len+1);
  5727.         if (recall[current])
  5728.           ckstrncpy(recall[current],s,len+1);
  5729.     }
  5730.     }
  5731. #endif /* CK_RECALL */
  5732. }
  5733.  
  5734.  
  5735. #ifdef CK_RECALL
  5736.  
  5737. /* C M H I S T O R Y */
  5738.  
  5739. VOID
  5740. cmhistory() {
  5741.     int i, lc = 1;
  5742.     for (i = 0; i <= current; i++) {
  5743.     printf(" %s\n", recall[i]);
  5744.     if (++lc > (cmd_rows - 2)) {    /* Screen full? */
  5745.         if (!askmore())        /* Do more-prompting... */
  5746.           break;
  5747.         else
  5748.           lc = 0;
  5749.     }
  5750.     }
  5751. }
  5752.  
  5753. int
  5754. savhistory(s,disp) char *s; int disp; {
  5755.     FILE * fp;
  5756.     int i;
  5757.  
  5758.     fp = fopen(s, disp ? "a" : "w");
  5759.     if (!fp) {
  5760.     perror(s);
  5761.     return(0);
  5762.     }
  5763.     for (i = 0; i <= current; i++)
  5764.       fprintf(fp,"%s\n", recall[i]);
  5765.     fclose(fp);
  5766.     return(1);
  5767. }
  5768. #endif /* CK_RECALL */
  5769.  
  5770. #ifdef COMMENT
  5771. /* apparently not used */
  5772. int
  5773. cmgetlc(s) char * s; {            /* Get leading char */
  5774.     char c;
  5775.     while ((c = *s++) <= SP) {
  5776.     if (!c)
  5777.       break;
  5778.     }
  5779.     return(c);
  5780. }
  5781. #endif /* COMMENT */
  5782.  
  5783.  
  5784. /*  C M C F M  --  Parse command confirmation (end of line)  */
  5785.  
  5786. /*
  5787.  Returns
  5788.    -2: User typed anything but whitespace or newline
  5789.    -1: Reparse needed
  5790.     0: Confirmation was received
  5791. */
  5792. int
  5793. cmcfm() {
  5794.     int x, xc;
  5795.     debug(F101,"cmcfm: cmflgs","",cmflgs);
  5796.     debug(F110,"cmcfm: atmbuf",atmbuf,0);
  5797.     inword = xc = cc = 0;
  5798.  
  5799.     setatm("",0);            /* (Probably unnecessary) */
  5800.  
  5801.     while (cmflgs != 1) {
  5802.         x = gtword(0);
  5803.         xc += cc;
  5804.  
  5805.         switch (x) {
  5806.       case -9:
  5807.         printf("Command or field too long\n");
  5808.       case -4:            /* EOF */
  5809.       case -2:
  5810.       case -1:
  5811.         return(x);
  5812.       case 1:            /* End of line */
  5813.         if (xc > 0) {
  5814.         if (xcmfdb) {
  5815.             return(-6);
  5816.         } else {
  5817.             printf("?Not confirmed - %s\n",atmbuf);
  5818.             return(-9);
  5819.         }
  5820.         } else
  5821.           break;            /* Finish up below */
  5822.       case 2:            /* ESC */
  5823.         if (xc == 0) {
  5824.         bleep(BP_WARN);
  5825.         continue;        /* or fall thru. */
  5826.         }
  5827.       case 0:            /* Space */
  5828.         if (xc == 0)        /* If no chars typed, continue, */
  5829.           continue;            /* else fall thru. */
  5830.         /* else fall thru... */
  5831.  
  5832.       case 3:            /* Question mark */
  5833.         if (xc > 0) {
  5834.         if (xcmfdb) {
  5835.             return(-6);
  5836.         } else {
  5837.             printf("?Not confirmed - %s\n",atmbuf);
  5838.             return(-9);
  5839.         }
  5840.         }
  5841.         printf(
  5842.            "\n Press the Return or Enter key to confirm the command\n");
  5843.         printf("%s%s",cmprom,cmdbuf);
  5844.         fflush(stdout);
  5845.         continue;
  5846.     }
  5847.     }
  5848.     debok = 1;
  5849.     return(0);
  5850. }
  5851.  
  5852.  
  5853. /* The following material supports chained parsing functions. */
  5854. /* See ckucmd.h for FDB and OFDB definitions. */
  5855.  
  5856. struct OFDB cmresult = {        /* Universal cmfdb result holder */
  5857.     NULL,                /* Address of succeeding FDB struct */
  5858.     0,                    /* Function code */
  5859.     NULL,                /* String result */
  5860.     0,                    /* Integer result */
  5861.     (CK_OFF_T)0                /* Wide result */
  5862. };
  5863.  
  5864. VOID
  5865. cmfdbi(p,fc,s1,s2,s3,n1,n2,f,k,nxt)    /* Initialize an FDB */
  5866.     struct FDB * p;
  5867.     int fc;
  5868.     char * s1, * s2, * s3;
  5869.     int n1, n2;
  5870.     xx_strp f;
  5871.     struct keytab * k;
  5872.     struct FDB * nxt; {
  5873.  
  5874.     p->fcode = fc;
  5875.     p->hlpmsg = s1;
  5876.     p->dflt = s2;
  5877.     p->sdata = s3;
  5878.     p->ndata1 = n1;
  5879.     p->ndata2 = n2;
  5880.     p->spf = f;
  5881.     p->kwdtbl = k;
  5882.     p->nxtfdb = nxt;
  5883. }
  5884.  
  5885. /*  C M F D B  --  Parse a field with several possible functions  */
  5886.  
  5887. int
  5888. cmfdb(fdbin) struct FDB * fdbin; {
  5889. #ifndef NOSPL
  5890.     extern int x_ifnum;                 /* IF NUMERIC - disables warnings */
  5891. #endif /* NOSPL */
  5892.     struct FDB * in = fdbin;
  5893.     struct OFDB * out = &cmresult;
  5894.     int x = 0, n, r;
  5895.     CK_OFF_T w = (CK_OFF_T)0;
  5896.     char *s, *xp, *m = NULL;
  5897.     int errbits = 0;
  5898.  
  5899.     xp = bp;
  5900.  
  5901.     out->fcode = -1;            /* Initialize output struct */
  5902.     out->fdbaddr = NULL;
  5903.     out->sresult = NULL;
  5904.     out->nresult = 0;
  5905. /*
  5906.   Currently we make one trip through the FDBs.  So if the user types Esc or
  5907.   Tab at the beginning of a field, only the first FDB is examined for a
  5908.   default.  If the user types ?, help is given only for one FDB.  We should
  5909.   search through the FDBs for all matching possibilities -- and in particular
  5910.   display the pertinent context-sensitive help for each function, rather than
  5911.   the only the first one that works, and then rewind the FDB pointer so we
  5912.   are not locked out of the earlier ones.
  5913. */
  5914.     cmfldflgs = 0;
  5915.     while (1) {                /* Loop through the chain of FDBs */
  5916.     nomsg = 1;
  5917.     xcmfdb = 1;
  5918.     s = NULL;
  5919.     n = 0;
  5920.     debug(F101,"cmfdb in->fcode","",in->fcode);
  5921.     switch (in->fcode) {        /* Current parsing function code */
  5922.       case _CMNUM:
  5923.         r = in->ndata1;
  5924.         if (r != 10 && r != 8) r = 10;
  5925. #ifndef NOSPL
  5926.             x_ifnum = 1;                /* Disables warning messages */
  5927. #endif /* NOSPL */
  5928.         x = cmnum(in->hlpmsg,in->dflt,r,&n,in->spf);
  5929. #ifndef NOSPL
  5930.             x_ifnum = 0;
  5931. #endif /* NOSPL */
  5932.         debug(F101,"cmfdb cmnum","",x);
  5933.         if (x < 0) errbits |= 1;
  5934.         break;
  5935.       case _CMNUW:            /* Wide cmnum - 24 Dec 2005 */
  5936.         r = in->ndata1;
  5937.         if (r != 10 && r != 8) r = 10;
  5938. #ifndef NOSPL
  5939.             x_ifnum = 1;                /* Disables warning messages */
  5940. #endif /* NOSPL */
  5941.         x = cmnumw(in->hlpmsg,in->dflt,r,&w,in->spf);
  5942. #ifndef NOSPL
  5943.             x_ifnum = 0;
  5944. #endif /* NOSPL */
  5945.         debug(F101,"cmfdb cmnumw","",w);
  5946.         if (x < 0) errbits |= 1;
  5947.         break;
  5948.       case _CMOFI:
  5949.         x = cmofi(in->hlpmsg,in->dflt,&s,in->spf);
  5950.         debug(F101,"cmfdb cmofi","",x);
  5951.         if (x < 0) errbits |= 2;
  5952.         break;
  5953.       case _CMIFI:
  5954.         x = cmifi2(in->hlpmsg,
  5955.                in->dflt,
  5956.                &s,
  5957.                &n,
  5958.                in->ndata1,
  5959.                in->sdata,
  5960.                in->spf,
  5961.                in->ndata2
  5962.                );
  5963.         debug(F101,"cmfdb cmifi2 x","",x);
  5964.         debug(F101,"cmfdb cmifi2 n","",n);
  5965.         if (x < 0) errbits |= 4;
  5966.         break;
  5967.       case _CMFLD:
  5968.         cmfldflgs = in->ndata1;
  5969.         x = cmfld(in->hlpmsg,in->dflt,&s,in->spf);
  5970.         debug(F101,"cmfdb cmfld","",x);
  5971.         if (x < 0) errbits |= 8;
  5972.         break;
  5973.       case _CMTXT:
  5974.         x = cmtxt(in->hlpmsg,in->dflt,&s,in->spf);
  5975.         debug(F101,"cmfdb cmtxt","",x);
  5976.         if (x < 0) errbits |= 16;
  5977.         break;
  5978.       case _CMKEY:
  5979.         x = cmkey2(in->kwdtbl,
  5980.                in->ndata1,
  5981.                in->hlpmsg,in->dflt,in->sdata,in->spf,in->ndata2);
  5982.         debug(F101,"cmfdb cmkey","",x);
  5983.         if (x < 0) errbits |= ((in->ndata2 & 4) ? 32 : 64);
  5984.         break;
  5985.       case _CMCFM:
  5986.         x = cmcfm();
  5987.         debug(F101,"cmfdb cmcfm","",x);
  5988.         if (x < 0) errbits |= 128;
  5989.         break;
  5990.       default:
  5991.         debug(F101,"cmfdb - unexpected function code","",in->fcode);
  5992.         printf("?cmfdb - unexpected function code: %d\n",in->fcode);
  5993.     }
  5994.     debug(F101,"cmfdb x","",x);
  5995.     debug(F101,"cmfdb cmflgs","",cmflgs);
  5996.     debug(F101,"cmfdb crflag","",crflag);
  5997.     debug(F101,"cmfdb qmflag","",qmflag);
  5998.     debug(F101,"cmfdb esflag","",esflag);
  5999.  
  6000.     if (x > -1) {            /* Success */
  6001.         out->fcode = in->fcode;    /* Fill in output struct */
  6002.         out->fdbaddr = in;
  6003.         out->sresult = s;
  6004.         out->nresult = (in->fcode == _CMKEY) ? x : n;
  6005.         out->wresult = w;
  6006.         out->kflags = (in->fcode == _CMKEY) ? cmkwflgs : 0;
  6007.         debug(F111,"cmfdb out->nresult",out->sresult,out->nresult);
  6008.         debug(F111,"cmfdb out->wresult",out->sresult,out->wresult);
  6009.         nomsg = 0;
  6010.         xcmfdb = 0;
  6011.         /* debug(F111,"cmfdb cmdbuf & crflag",cmdbuf,crflag); */
  6012.         if (crflag) {
  6013.         cmflgs = 1;
  6014.         }
  6015.         return(x);            /* and return */
  6016.     }
  6017.     in = in->nxtfdb;        /* Failed, get next parsing function */
  6018.     nomsg = 0;
  6019.     xcmfdb = 0;
  6020.     if (!in) {            /* No more */
  6021.         debug(F101,"cmfdb failure x","",x);
  6022.         debug(F101,"cmfdb failure errbits","",errbits);
  6023.         if (x == -6)
  6024.           x = -9;
  6025.         if (x == -9) {
  6026. #ifdef CKROOT
  6027.         if (ckrooterr)
  6028.           m = "Off Limits";
  6029.         else
  6030. #endif /* CKROOT */
  6031.         /* Make informative messages for a few common cases */
  6032.         switch (errbits) {
  6033.           case 4+32: m = "Does not match filename or switch"; break;
  6034.           case 4+64: m = "Does not match filename or keyword"; break;
  6035.           case 1+32: m = "Not a number or valid keyword"; break;
  6036.           case 1+64: m = "Not a number or valid switch"; break;
  6037.           default: m = "Not valid in this position";
  6038.         }
  6039.         printf("?%s: \"%s\"\n",m, atmbuf);
  6040.         }
  6041.         return(x);
  6042.     }
  6043.     if (x != -2 && x != -6 && x != -9 && x != -3) /* Editing or somesuch */
  6044.       return(x);            /* Go back and reparse */
  6045.     pp = np = bp = xp;        /* Back up pointers */
  6046.     cmflgs = -1;            /* Force a reparse */
  6047.  
  6048. #ifndef NOSPL
  6049.     if (!askflag) {            /* If not executing ASK-class cmd... */
  6050. #endif /* NOSPL */
  6051.         if (crflag) {        /* If CR was typed, put it back */
  6052.         pushc = LF;        /* But as a linefeed */
  6053.         } else if (qmflag) {    /* Ditto for Question mark */
  6054.         pushc = '?';
  6055.         } else if (esflag) {    /* and Escape or Tab */
  6056.         pushc = ESC;
  6057.         }
  6058. #ifndef NOSPL
  6059.     }
  6060. #endif /* NOSPL */
  6061.     }
  6062. }
  6063.  
  6064. /*
  6065.    C M I O F I  --  Parse an input file OR the name of a nonexistent file.
  6066.  
  6067.    Replaces the commented-out version above.  This one actually works and
  6068.    has the expected straightforward interface.
  6069. */
  6070. int
  6071. cmiofi(xhlp,xdef,xp,wild,f) char *xhlp, *xdef, **xp; int *wild; xx_strp f; {
  6072.     int x;
  6073.     struct FDB f1, f2;
  6074.     cmfdbi(&f1,_CMIFI,xhlp,xdef,"",0,0,f,NULL,&f2);
  6075.     cmfdbi(&f2,_CMOFI,"","","",0,0,f,NULL,NULL);
  6076.     x = cmfdb(&f1);
  6077.     if (x < 0) {
  6078.     if (x == -3) {
  6079.         x = -9;
  6080.         printf("?Filename required\n");
  6081.     }
  6082.     }
  6083.     *wild = cmresult.nresult;
  6084.     *xp = cmresult.sresult;
  6085.     return(x);
  6086. }
  6087.  
  6088. /*  G T W O R D  --  Gets a "word" from the command input stream  */
  6089.  
  6090. /*
  6091. Usage: retcode = gtword(brk);
  6092.   brk = 0 for normal word breaks (space, CR, Esc, ?)
  6093.   brk = 1 to add ':' and '=' (for parsing switches).  These characters
  6094.         act as break characters only if the first character of the field
  6095.         is slash ('/'), i.e. switch introducer.
  6096.   brk = 4 to not strip comments (used only for "help #" and "help ;").
  6097.  
  6098. Returns:
  6099. -10 Timelimit set and timed out
  6100.  -9 if input was too long
  6101.  -4 if end of file (e.g. pipe broken)
  6102.  -3 if null field
  6103.  -2 if command buffer overflows
  6104.  -1 if user did some deleting
  6105.   0 if word terminates with SP or tab
  6106.   1 if ... CR
  6107.   2 if ... ESC
  6108.   3 if ... ? (question mark)
  6109.   4 if ... : or = and called with brk != 0
  6110.  
  6111. With:
  6112.   pp pointing to beginning of word in buffer
  6113.   bp pointing to after current position
  6114.   atmbuf containing a copy of the word
  6115.   cc containing the number of characters in the word copied to atmbuf
  6116. */
  6117.  
  6118. int
  6119. ungword() {                /* Unget a word */
  6120.     debug(F101,"ungword cmflgs","",cmflgs);
  6121.     if (ungw) return(0);
  6122.     cmfsav = cmflgs;
  6123.     ungw = 1;
  6124.     cmflgs = 0;
  6125.     return(0);
  6126. }
  6127.  
  6128. /* Un-un-get word.  Undo ungword() if it has been done. */
  6129.  
  6130. VOID
  6131. unungw() {
  6132.     debug(F010,"unungw atmbuf",atmbuf,0);
  6133.     if (ungw) {
  6134.     ungw = 0;
  6135.     cmflgs = cmfsav;
  6136.     atmbuf[0] = NUL;
  6137.     }
  6138. }
  6139.  
  6140. static int
  6141. gtword(brk) int brk; {
  6142.     int c;                              /* Current char */
  6143.     int quote = 0;                      /* Flag for quote character */
  6144.     int echof = 0;                      /* Flag for whether to echo */
  6145.     int comment = 0;            /* Flag for in comment */
  6146.     char *cp = NULL;            /* Comment pointer */
  6147.     int eintr = 0;            /* Flag for syscall interrupted */
  6148.     int bracelvl = 0;            /* nested brace counter [jrs] */
  6149.     int iscontd = 0;            /* Flag for continuation */
  6150.     int realtty = 0;            /* Stdin is really a tty */
  6151.     char firstnb  = NUL;
  6152.     char lastchar = NUL;
  6153.     char prevchar = NUL;
  6154.     char lbrace, rbrace;
  6155.     int dq = 0;                /* Doublequote flag */
  6156.     int dqn = 0;            /* and count */
  6157.     int isesc = 0;
  6158.  
  6159. #ifdef RTU
  6160.     extern int rtu_bug;
  6161. #endif /* RTU */
  6162.  
  6163. #ifdef IKSD
  6164.     extern int inserver;
  6165. #endif /* IKSD */
  6166.     extern int kstartactive;
  6167.  
  6168. #ifdef datageneral
  6169.     extern int termtype;                /* DG terminal type flag */
  6170.     extern int con_reads_mt;            /* Console read asynch is active */
  6171.     if (con_reads_mt) connoi_mt();      /* Task would interfere w/cons read */
  6172. #endif /* datageneral */
  6173.  
  6174. #ifdef COMMENT
  6175. #ifdef DEBUG
  6176.     if (deblog) {
  6177.     debug(F101,"gtword brk","",brk);
  6178.     debug(F101,"gtword cmfldflgs","",cmfldflgs);
  6179.     debug(F101,"gtword swarg","",swarg);
  6180.     debug(F101,"gtword dpx","",dpx);
  6181.     debug(F101,"gtword echof","",echof);
  6182. #ifndef NOSPL
  6183.     debug(F101,"gtword askflag","",askflag);
  6184.     debug(F101,"gtword timelimit","",timelimit);
  6185. #ifndef NOLOCAL
  6186. #ifndef NOXFER
  6187. #ifdef CK_AUTODL
  6188.     debug(F101,"gtword cmdadl","",cmdadl);
  6189. #endif /* CK_AUTODL */
  6190. #endif /* NOXFER */
  6191. #endif /* NOLOCAL */
  6192. #endif /* NOSPL */
  6193.     }
  6194. #endif /* DEBUG */
  6195. #endif /* COMMENT */
  6196.  
  6197.     realtty = is_a_tty(0);        /* Stdin is really a tty? */
  6198.  
  6199.     if (cmfldflgs & 1) {
  6200.     lbrace = '(';
  6201.     rbrace = ')';
  6202.     } else {
  6203.     lbrace = '{';
  6204.     rbrace = '}';
  6205.     }
  6206.     crflag = 0;
  6207.     qmflag = 0;
  6208.     esflag = 0;
  6209.  
  6210.     if (swarg) {            /* No leading space for switch args */
  6211.     inword = 1;
  6212.     swarg = 0;
  6213.     }
  6214.     if (ungw) {                /* Have a word saved? */
  6215. #ifdef M_UNGW
  6216.     /* Experimental code to allow ungetting multiple words. */
  6217.     /* See comments in ckmkey2() above. */
  6218.     int x;
  6219.     if (np > pp) pp = np;
  6220.     while (*pp == SP) pp++;
  6221.     if (!*pp) {
  6222.         ungw = 0;
  6223.         cmflgs = cmfsav;
  6224.     } else {
  6225.         if ((x = setatm(pp,2)) < 0) {
  6226.         printf("?Saved word too long\n");
  6227.         return(-9);
  6228.         }
  6229.         if (pp[x] >= SP) {
  6230.         char *p2;
  6231.         p2 = pp;
  6232.         p2 += x;
  6233.         while (*p2 == SP) p2++;
  6234.         if (*p2) {
  6235.             np = p2;
  6236.             ungword();
  6237.         }
  6238.         } else {
  6239.         ungw = 0;
  6240.         cmflgs = cmfsav;
  6241.         debug(F010,"gtword ungw return atmbuf",atmbuf,0);
  6242.         }
  6243.     }
  6244.     return(cmflgs);
  6245. #else
  6246.     /*
  6247.        You would think the following should be:
  6248.              while (*pp == SP) pp++;
  6249.            but you would be wrong -- making this change breaks GOTO.
  6250.         */
  6251.     while (*pp++ == SP) ;
  6252.     if (setatm(pp,2) < 0) {
  6253.         printf("?Saved word too long\n");
  6254.         return(-9);
  6255.     }
  6256.     ungw = 0;
  6257.     cmflgs = cmfsav;
  6258.     debug(F010,"gtword ungw return atmbuf",atmbuf,0);
  6259.     return(cmflgs);
  6260. #endif /* M_UNGW */
  6261.     }
  6262.     pp = np;                            /* Start of current field */
  6263.  
  6264. #ifdef COMMENT
  6265. #ifdef DEBUG
  6266.     if (deblog) {
  6267.     debug(F110,"gtword cmdbuf",cmdbuf,0);
  6268.     debug(F110,"gtword bp",bp,0);
  6269.     debug(F110,"gtword pp",pp,0);
  6270.     }
  6271. #endif /* DEBUG */
  6272. #endif /* COMMENT */
  6273.     {
  6274.     /* If we are reparsing we have to recount any braces or doublequotes */
  6275.     char * p = pp;
  6276.     char c;
  6277.     if (*p == '"')
  6278.       dq++;
  6279.     while ((c = *p++))
  6280.       if (c == lbrace)
  6281.         bracelvl++;
  6282.       else if (c == rbrace)
  6283.         bracelvl--;
  6284.       else if (dq && c == '"')
  6285.         dqn++;
  6286.     }
  6287.     while (bp < cmdbuf+CMDBL) {         /* Big get-a-character loop */
  6288.     echof = 0;            /* Assume we don't echo because */
  6289.     chsrc = 0;            /* character came from reparse buf. */
  6290. #ifdef BS_DIRSEP
  6291. CMDIRPARSE:
  6292. #endif /* BS_DIRSEP */
  6293.  
  6294.     c = *bp;
  6295.         if (!c) {            /* If no char waiting in reparse buf */
  6296.         if ((dpx
  6297. #ifndef NOSPL
  6298.          || echostars
  6299. #endif /* NOSPL */
  6300.          ) && (!pushc
  6301. #ifndef NOSPL
  6302.             || askflag
  6303. #endif /* NOSPL */
  6304.             ))        /* Get from tty, set echo flag */
  6305.           echof = 1;
  6306.         c = cmdgetc(timelimit);    /* Read a command character. */
  6307. #ifdef DEBUG
  6308.         debug(F101,"gtword c","",c);
  6309. #endif /* DEBUG */
  6310.  
  6311.         if (timelimit && c < -1) {    /* Timed out */
  6312.         return(-10);
  6313.         }
  6314.  
  6315. #ifndef NOXFER
  6316. /*
  6317.   The following allows packet recognition in the command parser.
  6318.   Presently it works only for Kermit packets, and if our current protocol
  6319.   happens to be anything besides Kermit, we simply force it to Kermit.
  6320.   We don't use the APC mechanism here for mechanical reasons, and also
  6321.   because this way, it works even with minimally configured interactive
  6322.   versions.  Add Zmodem later...
  6323. */
  6324. #ifdef CK_AUTODL
  6325.         if ((!local && cmdadl)    /* Autodownload enabled? */
  6326. #ifdef IKS_OPTION
  6327.         || TELOPT_SB(TELOPT_KERMIT).kermit.me_start
  6328. #endif /* IKS_OPTION */
  6329.         ) {
  6330.         int k;
  6331.         k = kstart((CHAR)c);    /* Kermit S or I packet? */
  6332.         if (k) {
  6333.             int ksign = 0;
  6334.             if (k < 0) {    /* Minus-Protocol? */
  6335. #ifdef NOSERVER
  6336.             goto noserver;    /* Need server mode for this */
  6337. #else
  6338.             ksign = 1;    /* Remember */
  6339.             k = 0 - k;    /* Convert to actual protocol */
  6340.             justone = 1;    /* Flag for protocol module */
  6341. #endif /* NOSERVER */
  6342.             } else
  6343.               justone = 0;
  6344.             k--;        /* Adjust kstart's return value */
  6345.             if (k == PROTO_K) {
  6346.             extern int protocol, g_proto;
  6347.             extern CHAR sstate;
  6348.             g_proto = protocol;
  6349.             protocol = PROTO_K; /* Crude... */
  6350.             sstate = ksign ? 'x' : 'v';
  6351.             cmdbuf[0] = NUL;
  6352.             return(-3);
  6353.             }
  6354.         }
  6355.         }
  6356. #ifdef NOSERVER
  6357.       noserver:
  6358. #endif /* NOSERVER */
  6359. #endif /* CK_AUTODL */
  6360. #endif /* NOXFER */
  6361.  
  6362.         chsrc = 1;            /* Remember character source is tty. */
  6363.         brkchar = c;
  6364.  
  6365. #ifdef IKSD
  6366.             if (inserver && c < 0) {    /* End of session? */
  6367.                 debug(F111,"gtword c < 0","exiting",c);
  6368.                 return(-4);             /* Cleanup and terminate */
  6369.             }
  6370. #endif /* IKSD */
  6371.  
  6372. #ifdef OS2
  6373.            if (c < 0) {            /* Error */
  6374.            if (c == -3) {        /* Empty word? */
  6375.            if (blocklvl > 0)    /* In a block */
  6376.              continue;        /* so keep looking for block end */
  6377.            else
  6378.              return(-3);    /* Otherwise say we got nothing */
  6379.            } else {            /* Not empty word */
  6380.            return(-4);        /* So some kind of i/o error */
  6381.            }
  6382.            }
  6383. #else
  6384. #ifdef MAC
  6385.        if (c == -3)            /* Empty word... */
  6386.          if (blocklvl > 0)
  6387.            continue;
  6388.          else
  6389.            return(-3);
  6390. #endif /* MAC */
  6391. #endif /* OS2 */
  6392.        if (c == EOF) {        /* This can happen if stdin not tty. */
  6393. #ifdef EINTR
  6394. /*
  6395.   Some operating and/or C runtime systems return EINTR for no good reason,
  6396.   when the end of the standard input "file" is encountered.  In cases like
  6397.   this, we get into an infinite loop; hence the eintr counter, which is reset
  6398.   to 0 upon each call to this routine.
  6399. */
  6400.         debug(F101,"gtword EOF","",errno);
  6401.         if (errno == EINTR && ++eintr < 4) /* When bg'd process is */
  6402.           continue;        /* fg'd again. */
  6403. #endif /* EINTR */
  6404.         return(-4);
  6405.         }
  6406.         c &= cmdmsk;        /* Strip any parity bit */
  6407.     }                /* if desired. */
  6408.  
  6409. /* Now we have the next character */
  6410.  
  6411.     isesc = (c == ESC);        /* A real ESC? */
  6412.  
  6413.     if (!firstnb && c > SP) {    /* First nonblank */
  6414.         firstnb = c;
  6415.         if (c == '"')        /* Starts with doublequote */
  6416.           dq = 1;
  6417.     }
  6418.     if (c == '"')            /* Count doublequotes */
  6419.       dqn++;
  6420.  
  6421.     if (quote && (c == CR || c == LF)) { /* Enter key following quote */
  6422.         *bp++ = CMDQ;        /* Double it */
  6423.         *bp = NUL;
  6424.         quote = 0;
  6425.     }
  6426.         if (quote == 0) {        /* If this is not a quoted character */
  6427.         switch (c) {
  6428.           case CMDQ:        /* Got the quote character itself */
  6429.         if (!comment && quoting)
  6430.           quote = 1;        /* Flag it if not in a comment */
  6431.         break;
  6432.           case FF:            /* Formfeed. */
  6433.                 c = NL;                 /* Replace with newline */
  6434.         cmdclrscn();        /* Clear the screen */
  6435.         break;
  6436.           case HT:            /* Horizontal Tab */
  6437.         if (comment)        /* If in comment, */
  6438.           c = SP;        /* substitute space */
  6439.         else            /* otherwise */
  6440.           c = ESC;        /* substitute ESC (for completion) */
  6441.         break;
  6442.           case ';':            /* Trailing comment */
  6443.           case '#':
  6444.         if (! (brk & 4) ) {    /* If not keeping comments */
  6445.             if (inword == 0 && quoting) { /* If not in a word */
  6446.             comment = 1;    /* start a comment. */
  6447.             cp = bp;    /* remember where it starts. */
  6448.             }
  6449.         }
  6450.         break;
  6451.         }
  6452.         if (!kstartactive &&    /* Not in possible Kermit packet */
  6453.         !comment && c == SP) {    /* Space not in comment */
  6454.                 *bp++ = (char) c;    /* deposit in buffer if not already */
  6455.         /* debug(F101,"gtword echof 2","",echof); */
  6456. #ifdef BEBOX
  6457.                 if (echof) {
  6458.             cmdecho((char) c, 0); /* Echo what was typed. */
  6459.                     fflush(stdout);
  6460.                     fflush(stderr);
  6461.                 }
  6462. #else
  6463.                 if (echof) {
  6464.             cmdecho((char) c, 0); /* Echo what was typed. */
  6465.             if (timelimit)
  6466.               fflush(stdout);
  6467.         }
  6468. #endif /* BEBOX */
  6469.                 if (inword == 0) {      /* If leading, gobble it. */
  6470.                     pp++;
  6471.                     continue;
  6472.                 } else {                /* If terminating, return. */
  6473.             if ((!dq && ((*pp != lbrace) || (bracelvl == 0))) ||
  6474.             (dq && dqn > 1 && *(bp-2) == '"')) {
  6475.             np = bp;
  6476.             cmbptr = np;
  6477.             if (setatm(pp,0) < 0) {
  6478.                 printf("?Field too long error 1\n");
  6479.                 debug(F111,"gtword too long #1",pp,strlen(pp));
  6480.                 return(-9);
  6481.             }
  6482.             brkchar = c;
  6483.             inword = cmflgs = 0;
  6484.             return(0);
  6485.             }
  6486.                     continue;
  6487.                 }
  6488.             }
  6489.             if (c == lbrace) {
  6490.         bracelvl++;
  6491.         /* debug(F101,"gtword bracelvl++","",bracelvl); */
  6492.         }
  6493.             if (c == rbrace && bracelvl > 0) {
  6494.                 bracelvl--;
  6495.         /* debug(F101,"gtword bracelvl--","",bracelvl); */
  6496.                 if (linebegin)
  6497.           blocklvl--;
  6498.             }
  6499.         if ((c == '=' || c == ':') &&
  6500.         /* ^^^ */
  6501.         !kstartactive && !comment && brk /* && (firstnb == '/') */
  6502.         ) {
  6503.                 *bp++ = (char) c;    /* Switch argument separator */
  6504.         /* debug(F111,"gtword switch argsep",cmdbuf,brk); */
  6505. #ifdef BEBOX
  6506.                 if (echof) {
  6507.             cmdecho((char) c, 0); /* Echo what was typed. */
  6508.                     fflush(stdout);
  6509.                     fflush(stderr);
  6510.                 }
  6511. #else
  6512.         if (echof) {
  6513.             cmdecho((char) c, 0); /* Echo what was typed. */
  6514.             if (timelimit)
  6515.               fflush(stdout);
  6516.         }
  6517. #endif /* BEBOX */
  6518.         if ((*pp != lbrace) || (bracelvl == 0)) {
  6519.             np = bp;
  6520.             cmbptr = np;
  6521.             if (setatm(pp,2) < 0) { /* ^^^ */
  6522.             printf("?Field too long error 1\n");
  6523.             debug(F111,"gtword too long #1",pp,strlen(pp));
  6524.             return(-9);
  6525.             }
  6526.             inword = cmflgs = 0;
  6527.             brkchar = c;
  6528.             return(4);
  6529.         }
  6530.             }
  6531.             if (c == LF || c == CR) {    /* CR or LF. */
  6532.         if (echof) {
  6533.                     cmdnewl((char)c);    /* echo it. */
  6534. #ifdef BEBOX
  6535.                     fflush(stdout);
  6536.                     fflush(stderr);
  6537. #endif /* BEBOX */
  6538.                 }
  6539.         {
  6540.             /* Trim trailing comment and whitespace */
  6541.             char *qq;
  6542.             if (comment) {    /* Erase comment */
  6543.             while (bp >= cp) /* Back to comment pointer */
  6544.               *bp-- = NUL;
  6545.             bp++;
  6546.             pp = bp;    /* Adjust other pointers */
  6547.             inword = 0;    /* and flags */
  6548.             comment = 0;
  6549.             cp = NULL;
  6550.             }
  6551.             qq = inword ? pp : (char *)cmdbuf;
  6552.             /* Erase trailing whitespace */
  6553.             while (bp > qq && (*(bp-1) == SP || *(bp-1) == HT)) {
  6554.             bp--;
  6555.             /* debug(F000,"erasing","",*bp); */
  6556.             *bp = NUL;
  6557.             }
  6558.             lastchar = (bp > qq) ? *(bp-1) : NUL;
  6559.             prevchar = (bp > qq+1) ? *(bp-2) : NUL;
  6560.         }
  6561.         if (linebegin && blocklvl > 0) /* Blank line in {...} block */
  6562.           continue;
  6563.  
  6564.         linebegin = 1;        /* At beginning of next line */
  6565.         iscontd = prevchar != CMDQ &&
  6566.           (lastchar == '-' || lastchar == lbrace);
  6567.         debug(F101,"gtword iscontd","",iscontd);
  6568.  
  6569.                 if (iscontd) {        /* If line is continued... */
  6570.                     if (chsrc) {    /* If reading from tty, */
  6571.                         if (*(bp-1) == lbrace) { /* Check for "begin block" */
  6572.                             *bp++ = SP;    /* Insert a space for neatness */
  6573.                             blocklvl++;    /* Count block nesting level */
  6574.                         } else {    /* Or hyphen */
  6575.                 bp--;    /* Overwrite the hyphen */
  6576.                         }
  6577.                         *bp = NUL;    /* erase the dash, */
  6578.                         continue;    /* and go back for next char now. */
  6579.                     }
  6580.         } else if (blocklvl > 0) { /* No continuation character */
  6581.             if (chsrc) {    /* But we're in a "block" */
  6582.             *bp++ = ',';    /* Add comma */
  6583.             *bp = NUL;
  6584.             continue;
  6585.             }
  6586.         } else {        /* No continuation, end of command. */
  6587.             *bp = NUL;        /* Terminate the command string. */
  6588.             if (comment) {    /* If we're in a comment, */
  6589.             comment = 0;    /* Say we're not any more, */
  6590.             *cp = NUL;    /* cut it off. */
  6591.             }
  6592.             np = bp;        /* Where to start next field. */
  6593.             cmbptr = np;
  6594.             if (setatm(pp,0) < 0) { /* Copy field to atom buffer */
  6595.             debug(F111,"gtword too long #2",pp,strlen(pp));
  6596.             printf("?Field too long error 2\n");
  6597.             return(-9);
  6598.             }
  6599.             inword = 0;        /* Not in a word any more. */
  6600.             crflag = 1;
  6601.                     /* debug(F110,"gtword","crflag is set",0); */
  6602. #ifdef CK_RECALL
  6603.             current = rlast;
  6604. #endif /* CK_RECALL */
  6605.             cmflgs = 1;
  6606.             if (!xcmdsrc
  6607. #ifdef CK_RECALL
  6608.             || force_add
  6609. #endif /* CK_RECALL */
  6610.             )
  6611.                 addcmd(cmdbuf);
  6612.             return(cmflgs);
  6613.         }
  6614.             }
  6615. /*
  6616.   This section handles interactive help, completion, editing, and history.
  6617.   Rearranged as a switch statement executed only if we're at top level since
  6618.   there is no need for any of this within command files and macros: Aug 2000.
  6619.   Jun 2001: Even if at top level, skip this if the character was fetched from
  6620.   the reparse or recall buffer, or if stdin is redirected.
  6621. */
  6622.         if ((xcmdsrc == 0        /* Only at top level */
  6623. #ifndef NOSPL
  6624.         || askflag        /* or user is typing ASK response */
  6625. #endif /* NOSPL */
  6626.          ) && chsrc != 0 && realtty) { /* from the real keyboard */
  6627.  
  6628. /* Use ANSI / VT100 up and down arrow keys for command recall.  */
  6629.  
  6630.         if (isesc && (
  6631. #ifdef IKSD
  6632.             inserver
  6633. #else
  6634.             0
  6635. #endif /* IKSD */
  6636. #ifdef USE_ARROWKEYS
  6637.                               || 1
  6638. #endif /* USE_ARROWKEYS */
  6639.                              )
  6640.                      ) {        /* A real ESC was typed */
  6641.             int x;
  6642.             msleep(200);    /* Wait 1/5 sec */
  6643.             x = cmdconchk();    /* Was it followed by anything? */
  6644.             debug(F101,"Arrowkey ESC cmdconchk","",x);
  6645.  
  6646.             if (x > 1) {    /* If followed by at least 2 chars */
  6647.             int c2;
  6648.             c2 = cmdgetc(0); /* Get the first one */
  6649.             debug(F101,"Arrowkey ESC c2","",c2);
  6650.  
  6651.             if (c2 != '[' && c2 != 'O') { /* If not [ or O */
  6652.                 pushc = c2;    /* Push it and take the ESC solo */
  6653.             } else {
  6654.                 c2 = cmdgetc(0); /* Get the second one */
  6655.                 debug(F101,"Arrowkey ESC c3","",c2);
  6656.                 switch (c2) {
  6657. #ifndef NORECALL
  6658.                   case 'A':    /* Up */
  6659.                 c = BEL;
  6660.                 c = C_UP;
  6661.                 break;
  6662.                   case 'B':    /* Down */
  6663.                 c = BEL;
  6664.                 c = C_DN;
  6665.                 break;
  6666.                   case 'C':    /* Right */
  6667.                   case 'D':    /* Left */
  6668. #else
  6669.                   default:
  6670. #endif /* NORECALL */
  6671.                 c = BEL; /* We don't use these yet */
  6672.                 break;
  6673.                 }
  6674.             }
  6675.             }
  6676.         }
  6677.  
  6678.         switch (c) {
  6679.           case '?':        /* ?-Help */
  6680. #ifndef NOSPL
  6681.             if (askflag)    /* No help in ASK response */
  6682.               break;
  6683. #endif /* NOSPL */
  6684.             if (quoting
  6685.             && !kstartactive
  6686.             && !comment
  6687.             ) {
  6688.             cmdecho((char) c, 0);
  6689.             *bp = NUL;
  6690.             if (setatm(pp,0) < 0) {
  6691.                 debug(F111,"gtword too long ?",pp,strlen(pp));
  6692.                 printf("?Too long\n");
  6693.                 return(-9);
  6694.             }
  6695.             qmflag = 1;
  6696.             return(cmflgs = 3);
  6697.             }
  6698.  
  6699.           case ESC:        /* Esc or Tab completion */
  6700.             if (!comment) {
  6701.             *bp = NUL;
  6702.             if (setatm(pp,0) < 0) {
  6703.                 debug(F111,"gtword too long Esc",pp,strlen(pp));
  6704.                 printf("?Too long\n");
  6705.                 return(-9);
  6706.             }
  6707.             esflag = 1;
  6708.             return(cmflgs = 2);
  6709.             } else {
  6710.             bleep(BP_WARN);
  6711.             continue;
  6712.             }
  6713.  
  6714.           case BS:        /* Character deletion */
  6715.           case RUB:
  6716.             if (bp > cmdbuf) {    /* If still in buffer... */
  6717.             cmdchardel();    /* erase it. */
  6718.             bp--;        /* point behind it, */
  6719.             if (*bp == lbrace) bracelvl--; /* Adjust brace count */
  6720.             if (*bp == rbrace) bracelvl++;
  6721.             if ((*bp == SP) && /* Flag if current field gone */
  6722.                 (*pp != lbrace || bracelvl == 0))
  6723.               inword = 0;
  6724.             *bp = NUL;    /* Erase character from buffer. */
  6725.             } else {        /* Otherwise, */
  6726.             bleep(BP_WARN);
  6727.             cmres();    /* and start parsing a new command. */
  6728.             *bp = *atmbuf = NUL;
  6729.             }
  6730.             if (pp < bp)
  6731.               continue;
  6732.             else
  6733.               return(cmflgs = -1);
  6734.  
  6735.           case LDEL:        /* ^U, line deletion */
  6736.             while ((bp--) > cmdbuf) {
  6737.             cmdchardel();
  6738.             *bp = NUL;
  6739.             }
  6740.             cmres();        /* Restart the command. */
  6741.             *bp = *atmbuf = NUL;
  6742.             inword = 0;
  6743.             return(cmflgs = -1);
  6744.  
  6745.           case WDEL:        /* ^W, word deletion */
  6746.             if (bp <= cmdbuf) {    /* Beep if nothing to delete */
  6747.             bleep(BP_WARN);
  6748.             cmres();
  6749.             *bp = *atmbuf = NUL;
  6750.             return(cmflgs = -1);
  6751.             }
  6752.             bp--;
  6753.             /* Back up over any trailing nonalphanums */
  6754.             /* This is dependent on ASCII collating sequence */
  6755.             /* but isalphanum() is not available everywhere. */
  6756.             for ( ;
  6757.              (bp >= cmdbuf) &&
  6758.              ((*bp < '0') ||
  6759.              ((*bp > '9') && (*bp < '@')) ||
  6760.              ((*bp > 'Z') && (*bp < 'a')) ||
  6761.              (*bp > 'z'));
  6762.              bp--
  6763.              ) {
  6764.             cmdchardel();
  6765.             *bp = NUL;
  6766.             }
  6767.             /* Now delete back to rightmost remaining nonalphanum */
  6768.             for ( ; (bp >= cmdbuf) && (*bp) ; bp--) {
  6769.             if ((*bp < '0') ||
  6770.                 (*bp > '9' && *bp < '@') ||
  6771.                 (*bp > 'Z' && *bp < 'a') ||
  6772.                 (*bp > 'z'))
  6773.               break;
  6774.             cmdchardel();
  6775.             *bp = NUL;
  6776.             }
  6777.             bp++;
  6778.             inword = 0;
  6779.             return(cmflgs = -1);
  6780.  
  6781.           case RDIS: {        /* ^R, redisplay */
  6782.               char *cpx; char cx;
  6783.               *bp = NUL;
  6784.               printf("\n%s",cmprom);
  6785.               cpx = cmdbuf;
  6786.               while ((cx = *cpx++)) {
  6787.               cmdecho(cx,0);
  6788.               }
  6789.               fflush(stdout);
  6790.               continue;
  6791.           }
  6792. #ifndef NOLASTFILE
  6793.           case VT:
  6794.             if (lastfile) {
  6795.             printf("%s ",lastfile);
  6796. #ifdef GEMDOS
  6797.             fflush(stdout);
  6798. #endif /* GEMDOS */
  6799.             inword = cmflgs = 0;
  6800.             addbuf(lastfile);    /* Supply default. */
  6801.             if (setatm(lastfile,0) < 0) {
  6802.                 printf("Last name too long\n");
  6803.                 if (np) free(np);
  6804.                 return(-9);
  6805.             }
  6806.             } else {        /* No default */
  6807.             bleep(BP_WARN);
  6808.             }
  6809.             return(0);
  6810. #endif    /* NOLASTFILE */
  6811.         }
  6812.  
  6813. #ifdef CK_RECALL
  6814.         if (on_recall &&    /* Reading commands from keyboard? */
  6815.             (cm_recall > 0) &&    /* Saving commands? */
  6816.             (c == C_UP || c == C_UP2)) { /* Go up one */
  6817.             if (last_recall == 2 && current > 0)
  6818.               current--;
  6819.             if (current < 0) {    /* Nowhere to go, */
  6820.             bleep(BP_WARN);
  6821.             continue;
  6822.             }
  6823.             if (recall[current]) { /* We have a previous command */
  6824.             while ((bp--) > cmdbuf) { /* Erase current line */
  6825.                 cmdchardel();
  6826.                 *bp = NUL;
  6827.             }
  6828.             ckstrncpy(cmdbuf,recall[current],CMDBL);
  6829. #ifdef OSK
  6830.             fflush(stdout);
  6831.             write(fileno(stdout), "\r", 1);
  6832.             printf("%s%s",cmprom,cmdbuf);
  6833. #else
  6834.             printf("\r%s%s",cmprom,cmdbuf);
  6835. #endif /* OSK */
  6836.             current--;
  6837.             }
  6838.             last_recall = 1;
  6839.             return(cmflgs = -1); /* Force a reparse */
  6840.         }
  6841.         if (on_recall &&    /* Reading commands from keyboard? */
  6842.             (cm_recall > 0) &&    /* Saving commands? */
  6843.             (c == C_DN)) {    /* Down one */
  6844.             int x = 1;
  6845.             if (last_recall == 1)
  6846.               x++;
  6847.             if (current + x > rlast) { /* Already at bottom, beep */
  6848.             bleep(BP_WARN);
  6849.             continue;
  6850.             }
  6851.             current += x;    /* OK to go down */
  6852.             if (recall[current]) {
  6853.             while ((bp--) > cmdbuf) { /* Erase current line */
  6854.                 cmdchardel();
  6855.                 *bp = NUL;
  6856.             }
  6857.             ckstrncpy(cmdbuf,recall[current],CMDBL);
  6858. #ifdef OSK
  6859.             fflush(stdout);
  6860.             write(fileno(stdout), "\r", 1);
  6861.             printf("%s%s",cmprom,cmdbuf);
  6862. #else
  6863.             printf("\r%s%s",cmprom,cmdbuf);
  6864. #endif /* OSK */
  6865.             last_recall = 2;
  6866.             return(cmflgs = -1); /* Force reparse */
  6867.             }
  6868.         }
  6869. #endif /* CK_RECALL */
  6870.         }
  6871.  
  6872.         if (c < SP && quote == 0) { /* Any other unquoted control char */
  6873.         if (!chsrc) {        /* If cmd file, point past it */
  6874.             bp++;
  6875.         } else {
  6876.             bleep(BP_WARN);
  6877.         }
  6878.         continue;        /* continue, don't put in buffer */
  6879.         }
  6880.         linebegin = 0;        /* Not at beginning of line */
  6881. #ifdef BEBOX
  6882.         if (echof) {
  6883.                 cmdecho((char) c, 0);    /* Echo what was typed. */
  6884.                 fflush (stdout);
  6885.                 fflush(stderr);
  6886.             }
  6887. #else
  6888. #ifdef NOSPL
  6889.             if (echof || chsrc)
  6890. #else
  6891.             if (echof || (echostars && chsrc))
  6892. #endif    /* NOSPL */
  6893.           cmdecho((char) c, 0);    /* Echo what was typed. */
  6894. #endif /* BEBOX */
  6895.         } else {            /* This character was quoted. */
  6896.         int qf = 1;
  6897.         quote = 0;            /* Unset the quote flag. */
  6898.         /* debug(F000,"gtword quote 0","",c); */
  6899.         /* Quote character at this level is only for SP, ?, and controls */
  6900.             /* If anything else was quoted, leave quote in, and let */
  6901.         /* the command-specific parsing routines handle it, e.g. \007 */
  6902.         if (c > 32 && c != '?' && c != RUB && chsrc != 0) {
  6903.         /* debug(F000,"gtword quote 1","",c); */
  6904.         *bp++ = CMDQ;        /* Deposit \ if it came from tty */
  6905.         qf = 0;            /* and don't erase it from screen */
  6906.         linebegin = 0;        /* Not at beginning of line */
  6907. #ifdef BS_DIRSEP
  6908. /*
  6909.   This is a hack to handle "cd \" or "cd foo\" on OS/2 and similar systems.
  6910.   If we were called from cmdir() and the previous character was the quote
  6911.   character, i.e. backslash, and this character is the command terminator,
  6912.   then we stuff an extra backslash into the buffer without echoing, then
  6913.   we stuff the carriage return back in again, and go back and process it,
  6914.   this time with the quote flag off.
  6915. */
  6916.         } else if (dirnamflg && (c == CR || c == LF || c == SP)) {
  6917.         /* debug(F000,"gtword quote 2","",c); */
  6918.         *bp++ = CMDQ;
  6919.         linebegin = 0;        /* Not at beginning of line */
  6920.         *bp = (c == SP ? SP : CR);
  6921.         goto CMDIRPARSE;
  6922. #endif /* BS_DIRSEP */
  6923.         }
  6924. #ifdef BEBOX
  6925.         if (echof) {
  6926.                 cmdecho((char) c, qf);    /* Echo what was typed. */
  6927.                 fflush (stdout);
  6928.                 fflush(stderr);
  6929.             }
  6930. #else
  6931.         if (echof) cmdecho((char) c, qf); /* Now echo quoted character */
  6932. #endif /* BEBOX */
  6933.         /* debug(F111,"gtword quote",cmdbuf,c); */
  6934.     }
  6935. #ifdef COMMENT
  6936.         if (echof) cmdecho((char) c,quote); /* Echo what was typed. */
  6937. #endif /* COMMENT */
  6938.         if (!comment) inword = 1;    /* Flag we're in a word. */
  6939.     if (quote) continue;        /* Don't deposit quote character. */
  6940.         if (c != NL) {            /* Deposit command character. */
  6941.         *bp++ = (char) c;        /* and make sure there is a NUL */
  6942. #ifdef COMMENT
  6943.         *bp = NUL;            /* after it */
  6944. #endif /* COMMENT */
  6945.     }
  6946.     }                                   /* End of big while */
  6947.     bleep(BP_WARN);
  6948.     printf("?Command too long, maximum length: %d.\n",CMDBL);
  6949.     cmflgs = -2;
  6950.     return(-9);
  6951. }
  6952.  
  6953. /* Utility functions */
  6954.  
  6955. /* A D D B U F  -- Add the string pointed to by cp to the command buffer  */
  6956.  
  6957. static int
  6958. addbuf(cp) char *cp; {
  6959.     int len = 0;
  6960.     while ((*cp != NUL) && (bp < cmdbuf+CMDBL)) {
  6961.         *bp++ = *cp++;                  /* Copy and */
  6962.         len++;                          /* count the characters. */
  6963.     }
  6964.     *bp++ = SP;                         /* Put a space at the end */
  6965.     *bp = NUL;                          /* Terminate with a null */
  6966.     np = bp;                            /* Update the next-field pointer */
  6967.     cmbptr = np;
  6968.     return(len);                        /* Return the length */
  6969. }
  6970.  
  6971. /*  S E T A T M  --  Deposit a token in the atom buffer.  */
  6972. /*
  6973.   Break on space, newline, carriage return, or NUL.
  6974.   Call with:
  6975.     cp = Pointer to string to copy to atom buffer.
  6976.     fcode = 0 means break on whitespace or EOL.
  6977.     fcode = 1 means don't break on space.
  6978.     fcode = 2 means break on space, ':', or '='.
  6979.     fcode = 3 means copy the whole string.
  6980.   Null-terminate the result.
  6981.   Return length of token, and also set global "cc" to this length.
  6982.   Return -1 if token was too long.
  6983. */
  6984. static int
  6985. setatm(cp,fcode) char *cp; int fcode; {
  6986.     char *ap, *xp, *dqp = NULL, lbrace, rbrace;
  6987.     int bracelvl = 0, dq = 0;
  6988.  
  6989.     register char * s;
  6990.     register int n = 0;
  6991.  
  6992.     if (cmfldflgs & 1) {        /* Handle grouping */
  6993.     lbrace = '(';
  6994.     rbrace = ')';
  6995.     } else {
  6996.     lbrace = '{';
  6997.     rbrace = '}';
  6998.     }
  6999.     cc = 0;                /* Character counter */
  7000.     ap = atmbuf;            /* Address of atom buffer */
  7001.  
  7002.     s = cp;
  7003.  
  7004.     while (*s++) n++;            /* Save a call to strlen */
  7005.  
  7006.     if (n > ATMBL) {
  7007.     printf("?Command buffer overflow\n");
  7008.     return(-1);
  7009.     }
  7010.     /* debug(F111,"setatm",cp,n); */
  7011.     if (cp == ap) {            /* In case source is atom buffer */
  7012.     xp = atybuf;            /* make a copy */
  7013. #ifdef COMMENT
  7014.     strncpy(xp,ap,ATMBL);        /* so we can copy it back, edited. */
  7015.     cp = xp;
  7016. #else
  7017.     s = ap;
  7018.     while ((*xp++ = *s++)) ;    /* We already know it's big enough */
  7019.     cp = xp = atybuf;
  7020. #endif /* COMMENT */
  7021.     }
  7022.     *ap = NUL;                /* Zero the atom buffer */
  7023.     if (fcode == 1) {            /* Trim trailing blanks */
  7024.     while (--n >= 0 && cp[n] == SP)
  7025.       ;
  7026.     cp[n+1] = NUL;
  7027.     }
  7028.     while (*cp == SP) {            /* Trim leading spaces */
  7029.     cp++;
  7030.     n--;
  7031.     }
  7032.     if (*cp == '"') {            /* Starts with doublequote? */
  7033.     dq = 1;
  7034.     dqp = cp;
  7035.     }
  7036.     while (*cp) {
  7037.         if (*cp == lbrace)
  7038.       bracelvl++;
  7039.         else if (*cp == rbrace)
  7040.       bracelvl--;
  7041.     if (bracelvl < 0)
  7042.       bracelvl = 0;
  7043.     if (bracelvl == 0) {
  7044.         if (dq) {
  7045.         if (*cp == SP || *cp == HT) {
  7046.             if (cp > dqp+1) {
  7047.             if (*(cp-1) == '"' && *(cp-2) != CMDQ) {
  7048.                 break;
  7049.             }
  7050.             }
  7051.         }
  7052.         } else if ((*cp == SP || *cp == HT) && fcode != 1 && fcode != 3)
  7053.           break;
  7054.         if ((fcode == 2) && (*cp == '=' || *cp == ':')) break;
  7055.         if ((fcode != 3) && (*cp == LF || *cp == CR)) break;
  7056.     }
  7057.         *ap++ = *cp++;
  7058.         cc++;
  7059.     }
  7060.     *ap = NUL;                /* Terminate the string. */
  7061.     /* debug(F111,"setatm result",atmbuf,cc); */
  7062.     return(cc);                         /* Return length. */
  7063. }
  7064.  
  7065. /*
  7066.   These functions attempt to hide system dependencies from the mainline
  7067.   code in gtword().  Dummy arg for cmdgetc() needed for compatibility with
  7068.   coninc(), ttinc(), etc, since a pointer to this routine can be passed in
  7069.   place of those to tn_doop().
  7070.  
  7071.   No longer static.  Used by askmore().  Fri Aug 20 15:03:34 1999.
  7072. */
  7073. #define CMD_CONINC            /* How we get keyboard chars */
  7074.  
  7075. int
  7076. cmdgetc(timelimit) int timelimit; {    /* Get a character from the tty. */
  7077.     int c;
  7078. #ifdef IKSD
  7079.     extern int inserver;
  7080. #endif /* IKSD */
  7081. #ifdef CK_LOGIN
  7082.     extern int x_logged;
  7083. #endif /* CK_LOGIN */
  7084. #ifdef TNCODE
  7085.     static int got_cr = 0;
  7086.     extern int ckxech;
  7087.     int tx = 0, is_tn = 0;
  7088. #endif /* TNCODE */
  7089.  
  7090.     if (pushc
  7091. #ifndef NOSPL
  7092.     && !askflag
  7093. #endif /* NOSPL */
  7094.     ) {
  7095.         debug(F111,"cmdgetc()","pushc",pushc);
  7096.     c = pushc;
  7097.     pushc = NUL;
  7098.     if (xcmfdb && c == '?')        /* Don't echo ? twice if chaining. */
  7099.       cmdchardel();
  7100.     return(c);
  7101.     }
  7102. #ifdef datageneral
  7103.     {
  7104.     char ch;
  7105.     c = dgncinb(0,&ch,1);        /* -1 is EOF, -2 TO,
  7106.                                          * -c is AOS/VS error */
  7107.     if (c == -2) {            /* timeout was enabled? */
  7108.         resto(channel(0));        /* reset timeouts */
  7109.         c = dgncinb(0,&ch,1);    /* retry this now! */
  7110.     }
  7111.     if (c < 0) return(-4);        /* EOF or some error */
  7112.     else c = (int) ch & 0177;    /* Get char without parity */
  7113. /*    echof = 1; */
  7114.     }
  7115. #else /* Not datageneral */
  7116. #ifndef MINIX2
  7117.     if (
  7118. #ifdef IKSD
  7119.     (!local && inserver) ||
  7120. #endif /* IKSD */
  7121.     timelimit > 0) {
  7122. #ifdef TNCODE
  7123.           GETNEXTCH:
  7124.             is_tn = !pushc && !local && sstelnet;
  7125. #endif /* TNCODE */
  7126. #ifdef COMMENT
  7127.         c = coninc(timelimit > 0 ? 1 : 0);
  7128. #else /* COMMENT */
  7129.         /* This is likely to break the asktimeout... */
  7130.         c = coninc(timelimit);
  7131. #endif /* COMMENT */
  7132.         /* debug(F101,"cmdgetc coninc","",c); */
  7133. #ifdef TNCODE
  7134.             if (c >= 0 && is_tn) {    /* Server-side Telnet */
  7135.                 switch (c) {
  7136.           case IAC:
  7137.                     /* debug(F111,"gtword IAC","c",c); */
  7138.                     got_cr = 0;
  7139.                     if ((tx = tn_doop((CHAR)(c & 0xff),ckxech,coninc)) == 0) {
  7140.                         goto GETNEXTCH;
  7141.                     } else if (tx <= -1) { /* I/O error */
  7142.                         /* If there was a fatal I/O error then ttclos()    */
  7143.                         /* has been called and the next GETNEXTCH attempt  */
  7144.                         /* will be !is_tn since ttclos() sets sstelnet = 0 */
  7145.                         doexit(BAD_EXIT,-1); /* (or return(-4)? */
  7146.                     } else if (tx == 1) { /* ECHO change */
  7147.                         ckxech = dpx = 1; /* Get next char */
  7148.                         goto GETNEXTCH;
  7149.                     } else if (tx == 2) { /* ECHO change */
  7150.                         ckxech = dpx = 0; /* Get next char */
  7151.                         goto GETNEXTCH;
  7152.                     } else if (tx == 3) { /* Quoted IAC */
  7153.                         c = 255;    /* proceeed with it. */
  7154.                     }
  7155. #ifdef IKS_OPTION
  7156.                     else if (tx == 4) {    /* IKS State Change */
  7157.                         goto GETNEXTCH;
  7158.                     }
  7159. #endif /* IKS_OPTION */
  7160.                     else if (tx == 6) {    /* Remote Logout */
  7161.             doexit(GOOD_EXIT,0);
  7162.                     } else {
  7163.             goto GETNEXTCH;    /* Unknown, get next char */
  7164.             }
  7165.                     break;
  7166. #ifdef COMMENT
  7167.                   case CR:
  7168.                     if (!TELOPT_U(TELOPT_BINARY)) {
  7169.             if (got_cr) {
  7170.                 /* This means the sender is violating Telnet   */
  7171.                 /* protocol because we received two CRs in a   */
  7172.                 /* row without getting either LF or NUL.       */
  7173.                 /* This will not solve the problem but it      */
  7174.                 /* will at least allow two CRs to do something */
  7175.                 /* whereas before the user would have to guess */
  7176.                 /* to send LF or NUL after the CR.             */
  7177.                 debug(F100,"gtword CR telnet error","",0);
  7178.                 c = LF;
  7179.             } else {
  7180.                 debug(F100,"gtword skipping CR","",0);
  7181.                 got_cr = 1;    /* Remember a CR was received */
  7182.                 goto GETNEXTCH;
  7183.             }
  7184.                     } else {
  7185.             debug(F100,"gtword CR to LF","",0);
  7186.             c = LF;
  7187.                     }
  7188.                     break;
  7189.                   case LF:
  7190.                     if (!TELOPT_U(TELOPT_BINARY)) {
  7191.             got_cr = 0;
  7192.             debug(F100,"gtword LF","",0);
  7193.                     } else {
  7194.             if (got_cr) {
  7195.                 got_cr = 0;
  7196.                 debug(F100,"gtword skipping LF","",0);
  7197.                 goto GETNEXTCH;
  7198.             }
  7199.                     }
  7200.                     break;
  7201.                   case NUL:
  7202.                     if (!TELOPT_U(TELOPT_BINARY) && got_cr) {
  7203.             c = LF;
  7204.             debug(F100,"gtword NUL to LF","",0);
  7205.                     } else {
  7206.             debug(F100,"gtword NUL","",0);
  7207.                     }
  7208.                     got_cr = 0;
  7209.                     break;
  7210. #else /* COMMENT */
  7211.                   case CR:
  7212.                     if ( !TELOPT_U(TELOPT_BINARY) && got_cr ) {
  7213.                         /* This means the sender is violating Telnet   */
  7214.                         /* protocol because we received two CRs in a   */
  7215.                         /* row without getting either LF or NUL.       */
  7216.                         /* This will not solve the problem but it      */
  7217.                         /* will at least allow two CRs to do something */
  7218.                         /* whereas before the user would have to guess */
  7219.                         /* to send LF or NUL after the CR.             */
  7220.                         debug(F100,"gtword CR telnet error","",0);
  7221.                     } else {
  7222.                         got_cr = 1;    /* Remember a CR was received */
  7223.                     }
  7224.                     /* debug(F100,"gtword CR to LF","",0); */
  7225.                     c = LF;
  7226.             break;
  7227.                   case LF:
  7228.                     if (got_cr) {
  7229.                         got_cr = 0;
  7230.                         /* debug(F100,"gtword skipping LF","",0); */
  7231.                         goto GETNEXTCH;
  7232.                     }
  7233.             break;
  7234.                   case NUL:
  7235.                     if (got_cr) {
  7236.                         got_cr = 0;
  7237.                         /* debug(F100,"gtword skipping NUL","",0); */
  7238.                         goto GETNEXTCH;
  7239. #ifdef COMMENT
  7240.                     } else {
  7241.                       debug(F100,"gtword NUL","",0);
  7242. #endif /* COMMENT */
  7243.                     }
  7244.                     break;
  7245. #endif /* COMMENT */
  7246. #ifdef IKSD
  7247.           case ETX:        /* Ctrl-C... */
  7248.                   case EOT:        /* EOT = EOF */
  7249.                       if (inserver
  7250. #ifdef CK_LOGIN
  7251.               && !x_logged
  7252. #endif /* CK_LOGIN */
  7253.               )
  7254.                           return(-4);
  7255.             break;
  7256. #endif /* IKSD */
  7257.           default:
  7258.                       got_cr = 0;
  7259.                 }
  7260.             }
  7261. #endif /* TNCODE */
  7262.     } else {
  7263. #ifdef OS2
  7264.     c = coninc(0);
  7265. #else /* OS2 */
  7266. #ifdef CMD_CONINC
  7267. #undef CMD_CONINC
  7268. #endif /* CMD_CONINC */
  7269.     c = getchar();
  7270. #endif /* OS2 */
  7271.     }
  7272. #else  /* MINIX2 */
  7273. #undef getc
  7274. #ifdef CMD_CONINC
  7275. #undef CMD_CONINC
  7276. #endif /* CMD_CONINC */
  7277.     c = getc(stdin);
  7278.     /* debug(F101,"cmdgetc getc","",c); */
  7279. #endif /* MINIX2 */
  7280. #ifdef RTU
  7281.     if (rtu_bug) {
  7282. #ifdef CMD_CONINC
  7283. #undef CMD_CONINC
  7284. #endif /* CMD_CONINC */
  7285.     c = getchar();            /* RTU doesn't discard the ^Z */
  7286.     rtu_bug = 0;
  7287.     }
  7288. #endif /* RTU */
  7289. #endif /* datageneral */
  7290.     return(c);                /* Return what we got */
  7291. }
  7292.  
  7293. /* #ifdef USE_ARROWKEYS */
  7294.  
  7295. /* Mechanism to use for peeking into stdin buffer */
  7296.  
  7297. #ifndef USE_FILE_CNT            /* stdin->__cnt */
  7298. #ifndef USE_FILE__CNT            /* Note: two underscores */
  7299. #ifdef HPUX                /* HPUX 7-11 */
  7300. #ifndef HPUX5
  7301. #ifndef HPUX6
  7302. #define USE_FILE__CNT
  7303. #endif /* HPUX6 */
  7304. #endif /* HPUX5 */
  7305. #else
  7306. #ifdef ANYSCO                /* SCO UNIX, OSR5, Unixware, etc */
  7307. #ifndef OLD_UNIXWARE            /* But not Unixware 1.x or 2.0 */
  7308. #ifndef UNIXWARE2            /* or 2.1.0 */
  7309. #define USE_FILE__CNT
  7310. #endif /* UNIXWARE2 */
  7311. #endif /* OLD_UNIXWARE */
  7312. #endif /* ANYSCO */
  7313. #endif /* HPUX */
  7314. #endif /* USE_FILE__CNT */
  7315. #endif /* USE_FILE_CNT */
  7316.  
  7317. #ifndef USE_FILE_R            /* stdin->_r */
  7318. #ifndef USE_FILE_CNT
  7319. #ifndef USE_FILE__CNT
  7320. #ifdef BSD44                /* {Free,Open,Net}BSD, BSDI */
  7321. #define USE_FILE_R
  7322. #endif /* BSD44 */
  7323. #endif /* USE_FILE__CNT */
  7324. #endif /* USE_FILE_CNT */
  7325. #endif /* USE_FILE_R */
  7326.  
  7327. #ifndef USE_FILE_R            /* stdin->_cnt */
  7328. #ifndef USE_FILE_CNT
  7329. #ifndef USE_FILE__CNT
  7330. #define USE_FILE_CNT            /* Everybody else (but Linux) */
  7331. #endif /* USE_FILE__CNT */
  7332. #endif /* USE_FILE_CNT */
  7333. #endif /* USE_FILE_R */
  7334.  
  7335.  
  7336. /*
  7337.   c m d c o n c h k
  7338.  
  7339.   How many characters are waiting to be read at the console?  Normally
  7340.   conchk() would tell us, but in Unix and VMS cmdgetc() uses stdio getchar(),
  7341.   thus bypassing coninc()/conchk(), so we have to peek into the stdin buffer,
  7342.   which is totally nonportable.  Which is why this routine is, at least for
  7343.   now, used only for checking for arrow-key sequences from the keyboard after
  7344.   an ESC was read.  Wouldn't it be nice if the stdio package had a function
  7345.   that returned the number of bytes waiting to be read from its buffer?
  7346.   Returns 0 or greater always.
  7347. */
  7348. int
  7349. cmdconchk() {
  7350.     int x = 0, y;
  7351.     y = pushc ? 1 : 0;            /* Have command character pushed? */
  7352. #ifdef OS2
  7353.     x = conchk();            /* Check device-driver buffer */
  7354.     if (x < 0) x = 0;
  7355. #else /* OS2 */
  7356. #ifdef CMD_CONINC            /* See cmdgetc() */
  7357.     x = conchk();            /* Check device-driver buffer */
  7358.     if (x < 0) x = 0;
  7359. #else  /* CMD_CONINC */
  7360.  
  7361. /* Here we must look inside the stdin buffer - highly platform dependent */
  7362.  
  7363. #ifdef _IO_file_flags            /* Linux */
  7364.     x = (int) ((stdin->_IO_read_end) - (stdin->_IO_read_ptr));
  7365.     debug(F101,"cmdconchk _IO_file_flags","",x);
  7366. #else  /* _IO_file_flags */
  7367. #ifdef USE_FILE_CNT            /* Traditional */
  7368. #ifdef VMS
  7369.     debug(F101,"cmdconchk (*stdin)->_cnt","",(*stdin)->_cnt);
  7370.     x = (*stdin)->_cnt;
  7371. #else
  7372. #ifdef NOARROWKEYS
  7373.     debug(F101,"cmdconchk NOARROWKEYS x","",0);
  7374. #else
  7375.     debug(F101,"cmdconchk stdin->_cnt","",stdin->_cnt);
  7376.     x = stdin->_cnt;
  7377. #endif /* NOARROWKEYS */
  7378. #endif /* VMS */
  7379.     if (x == 0) x = conchk();
  7380.     if (x < 0) x = 0;
  7381. #else  /* USE_FILE_CNT */
  7382. #ifdef USE_FILE__CNT            /* HP-UX */
  7383.     debug(F101,"cmdconchk stdin->__cnt","",stdin->__cnt);
  7384.     x = stdin->__cnt;
  7385.     if (x == 0) x = conchk();
  7386.     if (x < 0) x = 0;
  7387. #else  /* USE_FILE_CNT */
  7388. #ifdef USE_FILE_R            /* FreeBSD, OpenBSD, etc */
  7389.     debug(F101,"cmdconchk stdin->_r","",stdin->_r);
  7390.     x = stdin->_r;
  7391.     if (x == 0) x = conchk();
  7392.     if (x < 0) x = 0;
  7393.  
  7394.     /* Fill in any others here... */
  7395.  
  7396. #endif /* USE_FILE_R */
  7397. #endif /* USE_FILE__CNT */
  7398. #endif /* USE_FILE_CNT */
  7399. #endif /* _IO_file_flags */
  7400. #endif /* CMD_CONINC */
  7401. #endif /* OS2 */
  7402.     return(x + y);
  7403. }
  7404. /* #endif */ /* USE_ARROWKEYS */
  7405.  
  7406.  
  7407. static VOID
  7408. cmdclrscn() {                /* Clear the screen */
  7409.     ck_cls();
  7410. }
  7411.  
  7412. static VOID                /* What to echo at end of command */
  7413. #ifdef CK_ANSIC
  7414. cmdnewl(char c)
  7415. #else
  7416. cmdnewl(c) char c;
  7417. #endif /* CK_ANSIC */
  7418. /* cmdnewl */ {
  7419. #ifdef OS2
  7420. #ifdef IKSD
  7421.     extern int inserver;
  7422.     if (inserver && c == LF)
  7423.       putchar(CR);
  7424. #endif /* IKSD */
  7425. #endif /* OS2 */
  7426.  
  7427.     putchar(c);                /* c is the terminating character */
  7428.  
  7429. #ifdef WINTCP                /* what is this doing here? */
  7430.     if (c == CR) putchar(NL);
  7431. #endif /* WINTCP */
  7432.  
  7433. /*
  7434.   A.A. Chernov, who sent in changes for FreeBSD, said we also needed this
  7435.   for SVORPOSIX because "setup terminal by termios and curses does
  7436.   not convert \r to \n, so additional \n needed in newline function."  But
  7437.   it is also very likely to result in unwanted blank lines.
  7438. */
  7439. #ifdef BSD44
  7440.     if (c == CR) putchar(NL);
  7441. #endif /* BSD44 */
  7442.  
  7443. #ifdef COMMENT
  7444.     /* OS2 no longer needs this as all CR are converted to NL in coninc() */
  7445.     /* This eliminates the ugly extra blank lines discussed above.        */
  7446. #ifdef OS2
  7447.     if (c == CR) putchar(NL);
  7448. #endif /* OS2 */
  7449. #endif /* COMMENT */
  7450. #ifdef aegis
  7451.     if (c == CR) putchar(NL);
  7452. #endif /* aegis */
  7453. #ifdef AMIGA
  7454.     if (c == CR) putchar(NL);
  7455. #endif /* AMIGA */
  7456. #ifdef datageneral
  7457.     if (c == CR) putchar(NL);
  7458. #endif /* datageneral */
  7459. #ifdef GEMDOS
  7460.     if (c == CR) putchar(NL);
  7461. #endif /* GEMDOS */
  7462. #ifdef STRATUS
  7463.     if (c == CR) putchar(NL);
  7464. #endif /* STRATUS */
  7465. }
  7466.  
  7467. static VOID
  7468. cmdchardel() {                /* Erase a character from the screen */
  7469. #ifndef NOSPL
  7470.     if (!echostars)
  7471. #endif    /* NOSPL */
  7472.       if (!dpx) return;
  7473. #ifdef datageneral
  7474.     /* DG '\b' is EM (^y or \031) */
  7475.     if (termtype == 1)
  7476.       /* Erase a character from non-DG screen, */
  7477.       dgncoub(1,"\010 \010",3);
  7478.     else
  7479. #endif /* datageneral */
  7480.       printf("\b \b");
  7481. #ifdef GEMDOS
  7482.     fflush(stdout);
  7483. #else
  7484. #ifdef BEBOX
  7485.     fflush(stdout);
  7486. #endif /* BEBOX */
  7487. #endif /* GEMDOS */
  7488. }
  7489.  
  7490. static VOID
  7491. #ifdef CK_ANSIC
  7492. cmdecho(char c, int quote)
  7493. #else
  7494. cmdecho(c,quote) char c; int quote;
  7495. #endif /* CK_ANSIC */
  7496. { /* cmdecho */
  7497. #ifdef NOSPL
  7498.     if (!dpx) return;
  7499. #else
  7500.     if (!echostars) {
  7501.     if (!dpx) return;
  7502.     } else {
  7503.     c = (char)echostars;
  7504.     }
  7505. #endif    /* NOSPL */
  7506.     /* Echo tty input character c */
  7507.     if (quote) {
  7508.     putchar(BS);
  7509.     putchar(SP);
  7510.     putchar(BS);
  7511. #ifdef isprint
  7512.     putchar((CHAR) (isprint(c) ? c : '^' ));
  7513. #else
  7514.     putchar((CHAR) ((c >= SP && c < DEL) ? c : '^'));
  7515. #endif /* isprint */
  7516.     } else {
  7517.     putchar(c);
  7518.     }
  7519. #ifdef OS2
  7520.     if (quote==1 && c==CR) putchar((CHAR) NL);
  7521. #endif /* OS2 */
  7522.     if (timelimit)
  7523.       fflush(stdout);
  7524. }
  7525.  
  7526. /* Return pointer to current position in command buffer. */
  7527.  
  7528. char *
  7529. cmpeek() {
  7530.     return(np);
  7531. }
  7532. #endif /* NOICP */
  7533.  
  7534.  
  7535. #ifdef NOICP
  7536. #include "ckcdeb.h"
  7537. #include "ckucmd.h"
  7538. #include "ckcasc.h"
  7539. #endif /* NOICP */
  7540.  
  7541. /*  X X E S C  --  Interprets backslash codes  */
  7542. /*  Returns the int value of the backslash code if it is > -1 and < 256 */
  7543. /*  and updates the string pointer to first character after backslash code. */
  7544. /*  If the argument is invalid, leaves pointer unchanged and returns -1. */
  7545.  
  7546. int
  7547. xxesc(s) char **s; {            /* Expand backslash escapes */
  7548.     int x, y, brace, radix;        /* Returns the int value */
  7549.     char hd = '9';            /* Highest digit in radix */
  7550.     char *p;
  7551.  
  7552.     p = *s;                /* pointer to beginning */
  7553.     if (!p) return(-1);            /* watch out for null pointer */
  7554.     x = *p++;                /* character at beginning */
  7555.     if (x != CMDQ) return(-1);        /* make sure it's a backslash code */
  7556.  
  7557.     x = *p;                /* it is, get the next character */
  7558.     if (x == '{') {            /* bracketed quantity? */
  7559.     p++;                /* begin past bracket */
  7560.     x = *p;
  7561.     brace = 1;
  7562.     } else brace = 0;
  7563.     switch (x) {            /* Start interpreting */
  7564.       case 'd':                /* Decimal radix indicator */
  7565.       case 'D':
  7566.     p++;                /* Just point past it and fall thru */
  7567.       case '0':                /* Starts with digit */
  7568.       case '1':
  7569.       case '2':  case '3':  case '4':  case '5':
  7570.       case '6':  case '7':  case '8':  case '9':
  7571.     radix = 10;            /* Decimal */
  7572.     hd = '9';            /* highest valid digit */
  7573.     break;
  7574.       case 'o':                /* Starts with o or O */
  7575.       case 'O':
  7576.     radix = 8;            /* Octal */
  7577.     hd = '7';            /* highest valid digit */
  7578.     p++;                /* point past radix indicator */
  7579.     break;
  7580.       case 'x':                /* Starts with x or X */
  7581.       case 'X':
  7582.     radix = 16;            /* Hexadecimal */
  7583.     p++;                /* point past radix indicator */
  7584.     break;
  7585.       default:                /* All others */
  7586. #ifdef COMMENT
  7587.     *s = p+1;            /* Treat as quote of next char */
  7588.     return(*p);
  7589. #else
  7590.     return(-1);
  7591. #endif /* COMMENT */
  7592.     }
  7593.     /* For OS/2, there are "wide" characters required for the keyboard
  7594.      * binding, i.e \644 and similar codes larger than 255 (byte).
  7595.      * For this purpose, give up checking for < 256. If someone means
  7596.      * \266 should result in \26 followed by a "6" character, he should
  7597.      * always write \{26}6 anyway.  Now, return only the lower byte of
  7598.      * the result, i.e. 10, but eat up the whole \266 sequence and
  7599.      * put the wide result 266 into a global variable.  Yes, that's not
  7600.      * the most beautiful programming style but requires the least
  7601.      * amount of changes to other routines.
  7602.      */
  7603.     if (*p == '{') {            /* Sun May 11 20:00:40 2003 */
  7604.     brace = 1;            /* Allow {} after radix indicator */
  7605.     p++;
  7606.     }
  7607.     if (radix <= 10) {            /* Number in radix 8 or 10 */
  7608.     for ( x = y = 0;
  7609.            (*p) && (*p >= '0') && (*p <= hd)
  7610. #ifdef OS2
  7611.                    && (y < 5) && (x*radix < KMSIZE);
  7612.               /* the maximum needed value \8196 is 4 digits long */
  7613.               /* while as octal it requires \1377, i.e. 5 digits */
  7614. #else
  7615.                    && (y < 3) && (x*radix < 256);
  7616. #endif /* OS2 */
  7617.           p++,y++) {
  7618.         x = x * radix + (int) *p - 48;
  7619.     }
  7620. #ifdef OS2
  7621.         wideresult = x;            /* Remember wide result */
  7622.         x &= 255;
  7623. #endif /* OS2 */
  7624.     if (y == 0 || x > 255) {    /* No valid digits? */
  7625.         *s = p;            /* point after it */
  7626.         return(-1);            /* return failure. */
  7627.     }
  7628.     } else if (radix == 16) {        /* Special case for hex */
  7629.     if ((x = unhex(*p++)) < 0) { *s = p - 1; return(-1); }
  7630.     if ((y = unhex(*p++)) < 0) { *s = p - 2; return(-1); }
  7631.     x = ((x << 4) & 0xF0) | (y & 0x0F);
  7632. #ifdef OS2
  7633.         wideresult = x;
  7634.         if ((y = unhex(*p)) >= 0) {
  7635.            p++;
  7636.        wideresult = ((x << 4) & 0xFF0) | (y & 0x0F);
  7637.            x = wideresult & 255;
  7638.         }
  7639. #endif /* OS2 */
  7640.     } else x = -1;
  7641.     if (brace && *p == '}' && x > -1)    /* Point past closing brace, if any */
  7642.       p++;
  7643.     *s = p;                /* Point to next char after sequence */
  7644.     return(x);                /* Return value of sequence */
  7645. }
  7646.  
  7647. int                    /* Convert hex string to int */
  7648. #ifdef CK_ANSIC
  7649. unhex(char x)
  7650. #else
  7651. unhex(x) char x;
  7652. #endif /* CK_ANSIC */
  7653. /* unhex */ {
  7654.  
  7655.     if (x >= '0' && x <= '9')        /* 0-9 is offset by hex 30 */
  7656.       return(x - 0x30);
  7657.     else if (x >= 'A' && x <= 'F')    /* A-F offset by hex 37 */
  7658.       return(x - 0x37);
  7659.     else if (x >= 'a' && x <= 'f')    /* a-f offset by hex 57 */
  7660.       return(x - 0x57);            /* (obviously ASCII dependent) */
  7661.     else return(-1);
  7662. }
  7663.  
  7664. /*  L O O K U P  --  Lookup the string in the given array of strings  */
  7665.  
  7666. /*
  7667.   Call this way:  v = lookup(table,word,n,&x);
  7668.  
  7669.     table - a 'struct keytab' table.
  7670.     word  - the target string to look up in the table.
  7671.     n     - the number of elements in the table.
  7672.     x     - address of an integer for returning the table array index,
  7673.         or NULL if you don't need a table index.
  7674.  
  7675.   The keyword table must be arranged in ascending alphabetical order;
  7676.   alphabetic case doesn't matter but letters are treated as lowercase
  7677.   for purposes of ordering; thus "^" and "_" come *before* the letters,
  7678.   not after them.
  7679.  
  7680.   Returns the keyword's associated value (zero or greater) if found,
  7681.   with the variable x set to the keyword-table index.  If is lookup()
  7682.   is not successful, it returns:
  7683.  
  7684.    -3 if nothing to look up (target was null),
  7685.    -2 if ambiguous,
  7686.    -1 if not found.
  7687.  
  7688.   A match is successful if the target matches a keyword exactly, or if
  7689.   the target is a prefix of exactly one keyword.  It is ambiguous if the
  7690.   target matches two or more keywords from the table.
  7691.  
  7692.   Lookup() is the critical routine in scripts and so is optimized with a
  7693.   simple static cache plus some other tricks.  Maybe it could be improved
  7694.   further with binary search or hash techniques but I doubt it since most
  7695.   keyword tables are fairly short.
  7696. */
  7697.  
  7698. #ifdef USE_LUCACHE            /* Lookup cache */
  7699. extern int lusize;            /* (initialized in ckuus5.c) */
  7700. extern char * lucmd[];
  7701. extern int luval[];
  7702. extern int luidx[];
  7703. extern struct keytab * lutab[];
  7704. long luhits = 0L;
  7705. long lucalls = 0L;
  7706. long xxhits = 0L;
  7707. long luloop = 0L;
  7708. #endif /* USE_LUCACHE */
  7709.  
  7710. int
  7711. lookup(table,cmd,n,x) char *cmd; struct keytab table[]; int n, *x; {
  7712.  
  7713.     register int i, m;
  7714.     int v, len, cmdlen = 0;
  7715.     char c = NUL, c1, *s;
  7716.  
  7717. /* Get 1st char of search object, if it's null return -3. */
  7718.  
  7719.     if (!cmd || n < 1)            /* Defense de nullarg */
  7720.       return(-3);
  7721.     c1 = *cmd;                /* First character */
  7722.     if (!c1)                /* Make sure there is one */
  7723.       return(-3);
  7724.     if (isupper(c1))            /* If letter make it lowercase */
  7725.       c1 = tolower(c1);
  7726.  
  7727. #ifdef USE_LUCACHE            /* lookup() cache */
  7728.     m = lusize;
  7729.     lucalls++;                /* Count this lookup() call */
  7730.     for (i = 0; i < m; i++) {        /* Loop thru cache */
  7731.     if (*(lucmd[i]) == c1) {    /* Same as 1st char of search item? */
  7732.         if (lutab[i] == table) {    /* Yes - same table too? */
  7733.         if (!strcmp(cmd,lucmd[i])) { /* Yes - compare */
  7734.             if (x) *x = luidx[i];    /* Match - return index */
  7735.             luhits++;                /* Count cache hit */
  7736.             return(luval[i]);        /* Return associated value */
  7737.         }
  7738.         }
  7739.     }
  7740.     }
  7741. #endif /* USE_LUCACHE */
  7742.  
  7743. /* Not null, not in cache, look it up */
  7744.  
  7745.     s = cmd;
  7746.     while (*s++) cmdlen++;        /* Length of target */
  7747. /*
  7748.   Quick binary search to find last table entry whose first character is
  7749.   lexically less than the first character of the search object.  This is
  7750.   the starting point of the next loop, which must go in sequence since it
  7751.   compares adjacent table entries.
  7752. */
  7753.     if (n < 5) {            /* Not worth it for small tables */
  7754.     i = 0;
  7755.     } else {
  7756.     int lo = 0;
  7757.     int hi = n;
  7758.     int count = 0;
  7759.     while (lo+2 < hi && ++count < 12) {
  7760.         i = lo + ((hi - lo) / 2);
  7761.         c = *(table[i].kwd);
  7762.         if (isupper(c)) c = tolower(c);
  7763.         if (c < c1) {
  7764.         lo = i;
  7765.         } else {
  7766.         hi = i;
  7767.         }
  7768.     }
  7769.     i = (c < c1) ? lo+1 : lo;
  7770. #ifdef USE_LUCACHE
  7771.     if (i > 0) xxhits++;
  7772. #endif /* USE_LUCACHE */
  7773.     }
  7774.     for ( ; i < n-1; i++) {
  7775. #ifdef USE_LUCACHE
  7776.     luloop++;
  7777. #endif /* USE_LUCACHE */
  7778.     v = 0;
  7779.     c = *(table[i].kwd);
  7780.     if (c) {
  7781.         if (isupper(c)) c = tolower(c);
  7782.  
  7783.         /* The following is a big performance booster but makes it */
  7784.         /* absolutely essential that all lookup() tables are in order. */
  7785.  
  7786.         if (c > c1)            /* Leave early if past our mark */
  7787.           return(-1);
  7788.  
  7789. #ifdef DEBUG
  7790.         /* Use LOG DEBUG to check */
  7791.  
  7792.         if (deblog) {
  7793.         if (ckstrcmp(table[i].kwd,table[i+1].kwd,0,0) > 0) {
  7794.             printf("TABLE OUT OF ORDER [%s] [%s]\n",
  7795.                table[i].kwd,table[i+1].kwd);
  7796.  
  7797.         }
  7798.         }
  7799. #endif /* DEBUG */
  7800.  
  7801.         if (c == c1) {
  7802.         len = 0;
  7803.         s = table[i].kwd;
  7804.         while (*s++) len++;
  7805.         if ((len == cmdlen && !ckstrcmp(table[i].kwd,cmd,len,0)) ||
  7806.             ((v = !ckstrcmp(table[i].kwd,cmd,cmdlen,0)) &&
  7807.              ckstrcmp(table[i+1].kwd,cmd,cmdlen,0))) {
  7808.             if (x) *x = i;
  7809.             return(table[i].kwval);
  7810.         }
  7811.         } else v = 0;
  7812.     }
  7813.         if (v) {            /* Ambiguous */
  7814.         if (x) *x = i;        /* Set index of first match */
  7815.         return(-2);
  7816.     }
  7817.     }
  7818.  
  7819. /* Last (or only) element */
  7820.  
  7821.     if (!ckstrcmp(table[n-1].kwd,cmd,cmdlen,0)) {
  7822.         if (x) *x = n-1;
  7823.     /* debug(F111,"lookup",table[i].kwd,table); */
  7824.         return(table[n-1].kwval);
  7825.     } else return(-1);
  7826. }
  7827.  
  7828. /*
  7829.   x l o o k u p
  7830.  
  7831.   Like lookup, but requires a full (but case-independent) match
  7832.   and does NOT require the table to be in order.
  7833. */
  7834. int
  7835. xlookup(table,cmd,n,x) struct keytab table[]; char *cmd; int n, *x; {
  7836.     register int i;
  7837.     int len, cmdlen, one = 0;
  7838.     register char c, c2, * s, * s2;
  7839.  
  7840.     if (!cmd) cmd = "";            /* Check args */
  7841.     if (!*cmd || n < 1) return(-3);
  7842.  
  7843.     c = *cmd;                /* First char of string to look up */
  7844.     if (!*(cmd+1)) {            /* Special handling for 1-char names */
  7845.     cmdlen = 1;
  7846.     if (isupper(c))
  7847.       c = tolower(c);
  7848.     one = 1;
  7849.     } else {
  7850.     cmdlen = 0;
  7851.     s = cmd;
  7852.     while (*s++) cmdlen++;
  7853.     c = *cmd;
  7854.     if (isupper(c))
  7855.       c = tolower(c);
  7856.     }
  7857.     if (cmdlen < 1)
  7858.       return(-3);
  7859.  
  7860.     for (i = 0; i < n; i++) {
  7861.     s = table[i].kwd;        /* This entry */
  7862.     if (!s) s = "";
  7863.     if (!*s) continue;        /* Empty table entry */
  7864.     c2 = *s;
  7865.     if (isupper(c2)) c2 = tolower(c2);
  7866.     if (c != c2) continue;        /* First char doesn't match */
  7867.     if (one) {            /* Name is one char long */
  7868.         if (!*(s+1)) {
  7869.         if (x) *x = i;
  7870.                 *cmd = c; 
  7871.         return(table[i].kwval);    /* So is table entry */
  7872.         }
  7873.     } else {            /* Otherwise do string comparison */
  7874.         s2 = s;
  7875.         len = 0;
  7876.         while (*s2++) len++;
  7877.         if (len == cmdlen && !ckstrcmp(s,cmd,-1,0)) {
  7878.         if (x) *x = i;
  7879.         return(table[i].kwval);
  7880.         }
  7881.     }
  7882.     }
  7883.     return(-1);
  7884. }
  7885.  
  7886. /* Reverse lookup */
  7887.  
  7888. char *
  7889. rlookup(table,n,x) struct keytab table[]; int n, x; {
  7890.     int i;
  7891.     for (i = 0; i < n; i++) {
  7892.         if (table[i].kwval == x)
  7893.       return(table[i].kwd);
  7894.     }
  7895.     return(NULL);
  7896. }
  7897.  
  7898. #ifndef NOICP
  7899. int
  7900. cmdsquo(x) int x; {
  7901.     quoting = x;
  7902.     return(1);
  7903. }
  7904.  
  7905. int
  7906. cmdgquo() {
  7907.     return(quoting);
  7908. }
  7909. #endif /* NOICP */
  7910.