home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / cku201.zip / ckclib.c < prev    next >
C/C++ Source or Header  |  2002-01-05  |  81KB  |  2,825 lines

  1. char * cklibv = "C-Kermit library, 8.0.031, 29 Jul 2001";
  2.  
  3. #define CKCLIB_C
  4.  
  5. /* C K C L I B . C  --  C-Kermit Library routines. */
  6.  
  7. /*
  8.   Author: Frank da Cruz <fdc@columbia.edu>,
  9.   Columbia University Academic Information Systems, New York City.
  10.  
  11.   Copyright (C) 1999, 2002,
  12.     Trustees of Columbia University in the City of New York.
  13.     All rights reserved.  See the C-Kermit COPYING.TXT file or the
  14.     copyright text in the ckcmai.c module for disclaimer and permissions.
  15. */
  16.  
  17. /*
  18.   General-purpose, system/platform/compiler-independent routines for use
  19.   by all modules.  Many are replacements for commonly used C library
  20.   functions that are not found on every platform, and/or that lack needed
  21.   functionality (e.g. caseless string search/compare) or safety features.
  22.  
  23.     ckstrncpy()  - Similar to strncpy() but different (see comments).
  24.     ckstrncat()  - Similar to strncat() but different (see comments).
  25.     chartostr()  - Converts a char to a string (self or ctrl char name).
  26.     ckstrchr()   - Portable strchr().
  27.     ckstrpbrk()  - Portable strpbrk().
  28.     cklower()    - Lowercase a string (in place).
  29.     ckupper()    - Uppercase a string (in place).
  30.     ckindex()    - Left or right index.
  31.     ckstrstr()   - Portable strstr().
  32.     ckitoa()     - Converts int to string.
  33.     ckuitoa()    - Converts unsigned int to string.
  34.     ckltoa()     - Converts long to string.
  35.     ckultoa()    - Converts unsigned long to string.
  36.     ckctoa()     - Converts char to string.
  37.     ckmakmsg()   - Constructs a message from 4 source strings.
  38.     ckmakxmsg()  - Constructs a message from 12 source strings.
  39.     ckmatch()    - Pattern matching.
  40.     ckmemcpy()   - Portable memcpy().
  41.     ckrchar()    - Rightmost character of a string.
  42.     ckstrcmp()   - Possibly caseless string comparison.
  43.     ckstrpre()   - Caseless string prefix comparison.
  44.     sh_sort()    - Sorts an array of strings, many options.
  45.     brstrip()    - Strips enclosing braces (and doublequotes).
  46.     makelist()   - Splits "{{item}{item}...}" into an array.
  47.     makestr()    - Careful malloc() front end.
  48.     xmakestr()   - ditto (see comments).
  49.     ckradix()    - Convert number radix (2-36).
  50.     b8tob64()    - Convert data to base 64.
  51.     b64tob8()    - Convert base 64 to data.
  52.     chknum()     - Checks if string is a (possibly signed) integer.
  53.     rdigits()    - Checks if string is composed only of decimal digits.
  54.     isfloat()    - Checks if string is a valid floating-point number.
  55.     parnam()     - Returns parity name string.
  56.     hhmmss()     - Converts seconds to hh:mm:ss string.
  57.     lset()       - Write fixed-length field left-adjusted into a record.
  58.     rset()       - Write fixed-length field right-adjusted into a record.
  59.     ulongtohex() - Converts an unsigned long to a hex string.
  60.     hextoulong() - Converts a hex string to an unsigned long.
  61.     cksplit()    - Splits a string into an array of words.
  62.  
  63.   Prototypes are in ckclib.h.
  64.  
  65.   Note: This module should not contain any extern declarations.
  66. */
  67. #include "ckcsym.h"
  68. #include "ckcdeb.h"
  69. #include "ckcasc.h"
  70.  
  71. /* Public variables */
  72.  
  73. int dblquo = 1; /* Nonzero if doublequotes can be used for grouping */
  74.  
  75. char *
  76. ccntab[] = {    /* Names of ASCII (C0) control characters 0-31 */
  77.     "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
  78.     "BS",  "HT",  "LF",  "VT",  "FF",  "CR",  "SO",  "SI",
  79.     "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
  80.     "CAN", "EM",  "SUB", "ESC", "FS",  "GS",  "RS",  "US"
  81. };
  82.  
  83. char *
  84. c1tab[] = {    /* Names of ISO 6429 (C1) control characters 0-32 */
  85.     "XXX", "XXX", "BPH", "NBH", "IND", "NEL", "SSA", "ESA",
  86.     "HTS", "HTJ", "VTS", "PLD", "PLU", "RI",  "SS2", "SS3",
  87.     "DCS", "PU1", "PU2", "STS", "CCH", "MW",  "SPA", "EPA",
  88.     "SOS", "XXX", "SCI", "CSI", "ST",  "OSC", "PM",  "APC", "NBS"
  89. };
  90.  
  91. #define RXRESULT 127
  92. static char rxdigits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  93. static char rxresult[RXRESULT+1];
  94.  
  95. /*  C K S T R N C P Y */
  96.  
  97. /*
  98.   Copies a NUL-terminated string into a buffer whose total length is given,
  99.   ensuring that the result is NUL-terminated even if it has to be truncated.
  100.  
  101.   Call with:
  102.     dest = pointer to destination buffer
  103.     src  = pointer to source string
  104.     len  = length of destination buffer (the actual length, not one less).
  105.  
  106.   Returns:
  107.     int, The number of bytes copied, 0 or more.
  108.  
  109.   NOTE: This is NOT a replacement for strncpy():
  110.    . strncpy() does not require its source string to be NUL-terminated.
  111.    . strncpy() does not necessarily NUL-terminate its result.
  112.    . strncpy() right-pads dest with NULs if it is longer than src.
  113.    . strncpy() treats the length argument as the number of bytes to copy.
  114.    . ckstrncpy() treats the length argument as the size of the dest buffer.
  115.    . ckstrncpy() doesn't dump core if given NULL string pointers.
  116.    . ckstrncpy() returns a number.
  117.  
  118.   Use ckstrncpy() when you want to:
  119.    . Copy an entire string into a buffer without overrun.
  120.    . Get the length of the string back.
  121.  
  122.   Use strncpy() when you want to:
  123.    . Copy a piece of a string.
  124. */
  125. int
  126. #ifdef CK_ANSIC
  127. ckstrncpy(char * dest, const char * src, int len)
  128. #else
  129. ckstrncpy(dest,src,len) char * dest, * src; int len;
  130. #endif /* CK_ANSIC */
  131. {
  132.     int i;
  133.     if (len < 1 || !src || !dest) {    /* Nothing or nowhere to copy */
  134.     if (dest) *dest = NUL;
  135.     return(0);
  136.     }
  137. #ifndef NOCKSTRNCPY
  138.     for (i = 0; src[i] && (i < len-1); i++) /* Args OK, copy */
  139.       dest[i] = src[i];
  140.     dest[i] = NUL;
  141. #else
  142.     i = strlen(src);
  143.     if (i > len) i = len;
  144.     strncpy(dest,src,i);
  145.     dest[len] = NUL;
  146. #endif /* NOCKSTRNCPY */
  147.     return(i);
  148. }
  149.  
  150. /*  C K S T R N C A T */
  151.  
  152. /*
  153.   Appends a NUL-terminated string to a buffer whose total length is given,
  154.   ensuring that the result is NUL-terminated even if it had to be truncated.
  155.  
  156.   Call with:
  157.     dest = pointer to destination buffer containing a null-terminated string
  158.     src  = pointer to null-terminated source string
  159.     len  = length of destination buffer (the actual length, not one less).
  160.  
  161.   Returns:
  162.     int, The number of bytes copied, 0 or more.
  163. */
  164. int
  165. #ifdef CK_ANSIC
  166. ckstrncat(char * dest, const char * src, int len)
  167. #else
  168. ckstrncat(dest,src,len) char * dest, * src; int len;
  169. #endif /* CK_ANSIC */
  170. {
  171.     register int i, j;
  172. #ifdef NOCKSTRNCPY
  173.     register char * s1, * s2;
  174. #endif /* NOCKSTRNCPY */
  175.     if (len < 1 || !src || !dest) {    /* Nothing or nowhere to copy */
  176.     if (dest) *dest = NUL;
  177.     return(0);
  178.     }
  179. #ifndef NOCKSTRNCPY
  180.     /* Args OK, copy */
  181.     for (i = 0, j = strlen(dest); src[i] && (i < len-j-1); i++)
  182.       dest[i+j] = src[i];
  183.     dest[i+j] = NUL;
  184. #else
  185.     j = 0;
  186.     s1 = dest;
  187.     while (*s1++) j++;            /* j = strlen(dest); */
  188.     s1--;                /* (back up over NUL) */
  189.  
  190.     i = 0;
  191.     s2 = src;
  192.     while (*s2++) i++;            /* i = strlen(src); */
  193.  
  194.     if (i > (len-j))
  195.       i = len - j;
  196.     if (i <= 0)
  197.       return(0);
  198.  
  199. #ifdef COMMENT
  200.     strncpy(&dest[j],src,i);
  201. #else
  202.     j = i;                /* This should be a bit faster...    */
  203.     s2 = src;                /* depends on strcpy implementation; */
  204.     while ((*s1++ = *s2++) && j--)    /* at least it shouldn't be slower.  */
  205.       ;
  206.     dest[len-1] = NUL;            /* In case of early exit. */
  207. #endif /* COMMENT */
  208.  
  209. #endif /* NOCKSTRNCPY */
  210.     return(i);
  211. }
  212.  
  213. /*  C K M A K M S G  */
  214.  
  215. /*
  216.    Constructs a message from up to 4 pieces with length checking.
  217.    Result is always NUL terminated.  Call with:
  218.      buf: Pointer to buffer for constructing message.
  219.      len: Length of buffer.
  220.      s1-s4: String pointers (can be NULL).
  221.    Returns:
  222.      0: Nothing was copied.
  223.      n: (positive number) n bytes copied, all args copied successfully.
  224.     -n: n bytes were copied, destination buffer not big enough for all.
  225.    Also see:
  226.      ckmakxmsg() -- accepts 12 string args.
  227.      ckitoa(), ckltoa(), ckctoa(), ckitox(), etc.
  228.      Use ckmak[x]msg() plus ck?to?() as a safe replacement for sprintf().
  229. */
  230. int
  231. #ifdef CK_ANSIC
  232. ckmakmsg(char * buf, int len, char *s1, char *s2, char *s3, char *s4)
  233. #else /* CK_ANSIC */
  234. ckmakmsg(buf,len,s1,s2,s3,s4) char *buf, *s1, *s2, *s3, *s4; int len;
  235. #endif /* CK_ANSIC */
  236. {
  237.     int i, n = 0, m = 0;
  238.     char *s;
  239.     char *p, *a[4];
  240.  
  241.     if (!buf) return(n);        /* No destination */
  242.     if (len < 1) return(n);        /* No size */
  243.  
  244.     s = buf;                /* Point to destination */
  245.     a[0] = s1; a[1] = s2; a[2] = s3; a[3] = s4;    /* Array of source strings */
  246.     for (i = 0; i < 4; i++) {        /* Loop thru array */
  247.     p = a[i];            /* Point to this element */
  248.     if (p) {            /* If pointer not null */
  249.         n = ckstrncpy(s,p,len);    /* Copy safely */
  250.         m += n;            /* Accumulate total */
  251.         if (p[n])            /* Didn't get whole thing? */
  252.           return(-m);        /* return indicating buffer full */
  253.         len -= n;            /* Deduct from space left */
  254.         s += n;            /* Otherwise advance dest pointer */
  255.     }
  256.     }
  257.     return(m);                /* Return total bytes copied */
  258. }
  259.  
  260.  
  261. /*  C K M A K X M S G  */
  262.  
  263. /*  Exactly like ckmakmsg(), but accepts 12 string arguments. */
  264.  
  265. int
  266. #ifdef CK_ANSIC
  267. ckmakxmsg(char * buf, int len,
  268.       char *s1, char *s2, char *s3, char  *s4, char  *s5, char *s6,
  269.       char *s7, char *s8, char *s9, char *s10, char *s11, char *s12)
  270. #else /* CK_ANSIC */
  271. ckmakxmsg(buf,len,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12)
  272.   char *buf, *s1, *s2, *s3, *s4, *s5, *s6, *s7, *s8, *s9, *s10, *s11, *s12;
  273.   int len;
  274. #endif /* CK_ANSIC */
  275. {
  276.     int i, n = 0, m = 0;
  277.     char *s;
  278.     char *p, *a[12];
  279.  
  280.     if (!buf) return(n);        /* No destination */
  281.     if (len < 1) return(n);        /* No size */
  282.  
  283.     s = buf;                /* Point to destination */
  284.     a[0] = s1; a[1] =  s2; a[2]  = s3;  a[3] = s4; /* Source-string array */
  285.     a[4] = s5; a[5] =  s6; a[6]  = s7;  a[7] = s8;
  286.     a[8] = s9; a[9] = s10; a[10] = s11; a[11] = s12;
  287.     for (i = 0; i < 12; i++) {        /* Loop thru array */
  288.     p = a[i];            /* Point to this element */
  289.     if (p) {            /* If pointer not null */
  290.         n = ckstrncpy(s,p,len);    /* Copy safely */
  291.         m += n;            /* Accumulate total */
  292.         if (p[n])            /* Didn't get whole thing? */
  293.           return(-m);        /* return indicating buffer full */
  294.         len -= n;            /* Deduct from space left */
  295.         s += n;            /* Otherwise advance dest pointer */
  296.     }
  297.     }
  298.     return(m);                /* Return total bytes copied */
  299. }
  300.  
  301. /*  C H A R T O S T R  */
  302.  
  303. /*  Converts a character to a string, interpreting controls.  */
  304.  
  305. char *
  306. chartostr(x) int x; {            /* Call with char x */
  307.     static char buf[2];            /* Returns string pointer. */
  308.     if (x < 32)
  309.       return(ccntab[x]);
  310.     if (x == 127)
  311.       return("DEL");
  312.     if (x > 127 && x < 161)
  313.       return(c1tab[x - 128]);
  314.     if (x == 0xAD)
  315.       return("SHY");
  316.     buf[1] = NUL;
  317.     buf[0] = (unsigned)(x & 0xff);
  318.     return((char *)buf);
  319. }
  320.  
  321. /*  C K R C H A R */
  322.  
  323. /*  Returns the rightmost character of the given null-terminated string */
  324.  
  325. int
  326. ckrchar(s) char * s; {
  327.     register CHAR c = '\0', *p;
  328.     p = (CHAR *)s;
  329.     if (!p) p = (CHAR *)"";        /* Null pointer == empty string */
  330.     if (!*p) return(0);
  331.     while (*p)                /* Crawl to end of string */
  332.       c = *p++;
  333.     return((unsigned)(c & 0xff));    /* Return final character */
  334. }
  335.  
  336. /*  C K S T R C H R  */
  337.  
  338. /*  Replacement for strchr(), which is not universal.  */
  339. /*  Call with:
  340.      s = pointer to string to look in.
  341.      c = character to look for.
  342.     Returns:
  343.      NULL if c not found in s or upon any kind of error, or:
  344.      pointer to first occurrence of c in s, searching from left to right.
  345. */
  346. char *
  347. #ifdef CK_ANSIC
  348. ckstrchr(char * s, char c)
  349. #else
  350. ckstrchr(s,c) char *s, c;
  351. #endif /* CK_ANSIC */
  352. /* ckstrchr */ {
  353.     if (!s)
  354.       return(NULL);
  355.     while (*s && *s != c)
  356.       s++;
  357.     return((*s == c) ? s : NULL);
  358. }
  359.  
  360. /*  C K S T R R C H R  */
  361.  
  362. /*  Replacement for strrchr(), which is not universal.  */
  363. /*  Call with:
  364.      s = pointer to string to look in.
  365.      c = character to look for.
  366.     Returns:
  367.      NULL if c not found in s or upon any kind of error, or:
  368.      pointer to first occurrence of c in s, searching from right to left.
  369. */
  370. char *
  371. #ifdef CK_ANSIC
  372. ckstrrchr(char * s, char c)
  373. #else
  374. ckstrrchr(s,c) char *s, c;
  375. #endif /* CK_ANSIC */
  376. /* ckstrchr */ {
  377.     char * s2 = NULL;
  378.     if (!s)
  379.       return(NULL);
  380.     while (*s) {
  381.     if (*s == c)
  382.       s2 = s;
  383.     s++;
  384.     }
  385.     return(s2);
  386. }
  387.  
  388.  
  389. /* C K S T R P B R K  --  Portable replacement for strpbrk()  */
  390.  
  391. /* Returns pointer to first char in s1 that is also in s2, or NULL */
  392.  
  393. char *
  394. ckstrpbrk(s1, s2) char * s1, * s2; {
  395.     char c1, c2, * s3;
  396.     if (!s1 || !s2) return(NULL);
  397.     if (!*s1 || !*s2) return(NULL);
  398.     while ((c1 = *s1++)) {
  399.     s3 = s2;
  400.     while ((c2 = *s3++)) {
  401.         if (c2 == c1)
  402.           return(s1-1);
  403.     }
  404.     }
  405.     return(NULL);
  406. }
  407.  
  408. /*  C K L O W E R  --  Lowercase a string IN PLACE */
  409.  
  410. /* Returns the length of the string */
  411.  
  412. int
  413. cklower(s) char *s; {
  414.     int n = 0;
  415.     if (!s) return(0);
  416.     while (*s) {
  417.         if (isupper(*s)) *s = (char) tolower(*s);
  418.         s++, n++;
  419.     }
  420.     return(n);
  421. }
  422.  
  423. /*  C K U P P E R  --  Uppercase a string IN PLACE */
  424.  
  425. /* Returns the length of the string */
  426.  
  427. int
  428. ckupper(s) char *s; {
  429.     int n = 0;
  430.     if (!s) return(0);
  431.     while (*s) {
  432.         if (islower(*s)) *s = (char) toupper(*s);
  433.         s++, n++;
  434.     }
  435.     return(n);
  436. }
  437.  
  438. /*  C K L T O A  --  Long to string  --  FOR DISCIPLINED USE ONLY  */
  439.  
  440. #define NUMBUF 1024
  441. static char numbuf[NUMBUF+32] = { NUL, NUL };
  442. static int numbp = 0;
  443. /*
  444.   ckltoa() and ckitoa() are like atol() and atoi() in the reverse direction,
  445.   returning a pointer to the string representation of the given number without
  446.   the caller having to worry about allocating or defining a buffer first.
  447.   They manage their own internal buffer, so successive calls return different
  448.   pointers.  However, to keep memory consumption from growing without bound,
  449.   the buffer recycles itself.  So after several hundred calls (depending on
  450.   the size of the numbers), some of the earlier pointers might well find
  451.   themselves referencing something different.  Moral: You can't win in C.
  452.   Therefore, these routines are intended mainly for generating numeric strings
  453.   for short-term use, e.g. for passing numbers in string form as parameters to
  454.   functions.  For long-term use, the result must be copied to a safe place.
  455. */
  456. char *
  457. #ifdef CK_ANSIC
  458. ckltoa(long n)
  459. #else
  460. ckltoa(n) long n;
  461. #endif /* CK_ANSIC */
  462. /* ckltoa */ {
  463.     char buf[32];            /* Internal working buffer */
  464.     char * p, * s, * q;
  465.     int k, x, len = 0, sign = 0;
  466.     if (n < 0L) {            /* Sign */
  467.     n = 0L - n;
  468.     sign = 1;
  469.     }
  470.     buf[31] = NUL;
  471.     for (k = 30; k > 0; k--) {        /* Convert number to string */
  472.     x = n % 10L;
  473.     buf[k] = x + '0';
  474.     n = n / 10L;
  475.     if (!n)
  476.       break;
  477.     }
  478.     if (sign) buf[--k] = '-';        /* Add sign if necessary */
  479.     len = 31 - k;
  480.     if (len + numbp > NUMBUF)
  481.       numbp = 0;
  482.     p = numbuf + numbp;
  483.     q = p;
  484.     s = buf + k;
  485.     while ((*p++ = *s++)) ;        /* Copy */
  486.     *p++ = NUL;
  487.     numbp += len+1;
  488.     return(q);                /* Return pointer */
  489. }
  490.  
  491. /*  C K U L T O A  --  Unsigned long to string  */
  492.  
  493. char *
  494. #ifdef CK_ANSIC
  495. ckultoa(unsigned long n)
  496. #else
  497. ckultoa(n) unsigned long n;
  498. #endif /* CK_ANSIC */
  499. /* ckltoa */ {
  500.     char buf[32];            /* Internal working buffer */
  501.     char * p, * s, * q;
  502.     int k, x, len = 0;
  503.     buf[31] = NUL;
  504.     for (k = 30; k > 0; k--) {        /* Convert number to string */
  505.     x = n % 10L;
  506.     buf[k] = x + '0';
  507.     n = n / 10L;
  508.     if (!n)
  509.       break;
  510.     }
  511.     len = 31 - k;
  512.     if (len + numbp > NUMBUF)
  513.       numbp = 0;
  514.     p = numbuf + numbp;
  515.     q = p;
  516.     s = buf + k;
  517.     while ((*p++ = *s++)) ;        /* Copy */
  518.     numbp += len+1;
  519.     return(q);                /* Return pointer */
  520. }
  521.  
  522. char *
  523. #ifdef CK_ANSIC
  524. ckltox(long n)                /* Long int to "0x.." hex string */
  525. #else
  526. ckltox(n) long n;
  527. #endif /* CK_ANSIC */
  528. /* ckltox */ {
  529.     char buf[32];            /* Internal working buffer */
  530.     char *p, *q, *s, *bp = buf + 2;
  531.     int k;
  532.     buf[0] = '0';
  533.     buf[1] = 'x';
  534.     sprintf(bp, "%lx", n);
  535.     k = strlen(bp);
  536.     if (k&1) {
  537.     sprintf(bp, "0%lx", n);
  538.     k++;
  539.     }
  540.     k += 2;                /* "0x" */
  541.     if (numbp + k >= NUMBUF)
  542.       numbp = 0;
  543.     p = numbuf + numbp;
  544.     q = p;
  545.     s = buf;
  546.     while ((*p++ = *s++)) ;        /* Copy */
  547.     *p++ = NUL;
  548.     numbp += k+1;
  549.     return(q);                /* Return pointer */
  550. }
  551.  
  552.  
  553. /*  C K I T O A  --  Int to string  -- FOR DISCIPLINED USE ONLY  */
  554.  
  555. char *
  556. ckitoa(n) int n; {            /* See comments with ckltoa(). */
  557.     long nn;
  558.     nn = n;
  559.     return(ckltoa(nn));
  560. }
  561.  
  562.  
  563. char *                    /* Unsigned int to string */
  564. ckuitoa(n) unsigned int n; {
  565.     unsigned long nn;
  566.     nn = n;
  567.     return(ckultoa(nn));
  568. }
  569.  
  570. char *
  571. ckitox(n) int n; {            /* Int to hex */
  572.     long nn;
  573.     nn = n;
  574.     return(ckltox(nn));
  575. }
  576.  
  577. char *
  578. #ifdef CK_ANSIC
  579. ckctoa(char c)                /* Char to string */
  580. #else
  581. ckctoa(c) char c;
  582. #endif
  583. /* ckctoa */ {
  584.     static char buf[32];
  585.     static int current = 0;
  586.     if (current >= 30)
  587.       current = 0;
  588.     buf[current++] = c;
  589.     buf[current++] = '\0';
  590.     return((char *)(buf + current - 2));
  591. }
  592.  
  593. char *
  594. #ifdef CK_ANSIC
  595. ckctox(CHAR c, int flag)        /* Unsigned char to hex */
  596. #else
  597. ckctox(c, flag) CHAR c; int flag;
  598. #endif
  599. /* ckctox */ {
  600.     static char buf[48];
  601.     static int current = 0;
  602.     int x;
  603.     char h;
  604.     if (current > 45)
  605.       current = 0;
  606.     x = (c >> 4) & 0x0f;
  607.     h = rxdigits[x];
  608.     if (!flag && isupper(rxdigits[x]))
  609.       h = tolower(rxdigits[x]);
  610.     buf[current++] = h;
  611.     x = c & 0x0f;
  612.     h = rxdigits[x];
  613.     if (!flag && isupper(rxdigits[x]))
  614.       h = tolower(rxdigits[x]);
  615.     buf[current++] = h;
  616.     buf[current++] = '\0';
  617.     return((char *)(buf + current - 3));
  618. }
  619.  
  620. /*  C K I N D E X  --  C-Kermit's index function  */
  621. /*
  622.   We can't depend on C libraries to have one, so here is our own.
  623.   Call with:
  624.     s1 - String to look for.
  625.     s2 - String to look in.
  626.      t - Offset from right or left of s2, 0 based; -1 for rightmost char in s2.
  627.      r - 0 for left-to-right search, non-0 for right-to-left.
  628.   icase  0 for case independence, non-0 if alphabetic case matters.
  629.   Returns 0 if string not found, otherwise a 1-based result.
  630.   Also returns 0 on any kind of error, e.g. junk parameters.
  631. */
  632. int
  633. ckindex(s1,s2,t,r,icase) char *s1, *s2; int t, r, icase; {
  634.     int len1 = 0, len2 = 0, i, j, x, ot = t; /* ot = original t */
  635.     char * s;
  636.  
  637.     if (!s1 || !s2) return(0);
  638.     s = s1;
  639.     while (*s++) len1++;        /* length of string to look for */
  640.     s = s2;
  641.     while (*s++) len2++;        /* length of string to look in */
  642.     s = s2;
  643.     if (t < 0) t = len2 - 1;
  644.  
  645.     j = len2 - len1;            /* length difference */
  646.  
  647.     if (j < 0 || (r == 0 && t > j))    /* search string is longer */
  648.       return(0);
  649.     if (r == 0) {            /* Index */
  650.     s = s2 + t;            /* Point to beginning of target */
  651.     for (i = 0; i <= (j - t); i++) { /* Now compare */
  652.         x = ckstrcmp(s1,s++,len1,icase);
  653.         if (!x)
  654.           return(i+1+t);
  655.     }
  656.     } else {                /* Reverse Index */
  657.         i = len2 - len1;        /* Where to start looking */
  658.         if (ot > 0)            /* Figure in offset if any */
  659.       i -= t;
  660.     for (j = i; j > -1; j--) {
  661.         if (!ckstrcmp(s1,&s2[j],len1,icase))
  662.           return(j+1);
  663.     }
  664.     }
  665.     return(0);
  666. }
  667.  
  668. /*  C K S T R S T R  --  Portable replacement for strstr()  */
  669.  
  670. /*  Returns pointer to first occurrence of s2 in s2, or NULL */
  671.  
  672. char *
  673. ckstrstr(s1, s2) char * s1, * s2; {
  674.     int k;
  675.     k = ckindex(s2,s1,0,0,1);
  676.     return((k < 1) ? NULL : &s1[k-1]);
  677. }
  678.  
  679.  
  680. /*  B R S T R I P  --  Strip enclosing braces from arg string, in place. */
  681. /*
  682.   Call with:
  683.     Pointer to string that can be poked.
  684.   Returns:
  685.     Pointer to string without enclosing braces.
  686.     If original string was not braced, this is the arg pointer;
  687.     otherwise it is 1 + the arg pointer, with the matching closing
  688.     brace zero'd out.  If the string starts with a brace but does
  689.     not end with a matching brace, the original pointer to the original
  690.     string is returned.  If the arg pointer is NULL, a pointer to an
  691.     empty string is returned.
  692. */
  693. #ifdef COMMENT
  694.  
  695. /* This is the original version, handling only braces */
  696.  
  697. char *
  698. brstrip(p) char *p; {
  699.     if (!p) return("");
  700.     if (*p == '{') {
  701.     int x;
  702.     x = (int)strlen(p) - 1;
  703.     if (p[x] == '}') {
  704.         p[x] = NUL;
  705.         p++;
  706.     }
  707.     }
  708.     return(p);
  709. }
  710.  
  711. #else
  712. /* New version handles braces and doublequotes */
  713.  
  714. char *
  715. brstrip(p) char *p; {
  716.     if (!p) return("");
  717.     if (*p == '{' || (*p == '"' && dblquo)) {
  718.     int x;
  719.     x = (int)strlen(p) - 1;
  720.     if (x > 0) {
  721.         if ((*p == '{' && p[x] == '}') ||
  722.         (*p == '"' && p[x] == '"')) {
  723.         if (x > 0 && p[x-1] != CMDQ) {
  724.             p[x] = NUL;
  725.             p++;
  726.         }
  727.         }
  728.     }
  729.     }
  730.     return(p);
  731. }
  732. #endif /* COMMENT */
  733.  
  734. #ifdef COMMENT
  735.  
  736. /* Even newer experimental version -- breaks many things */
  737.  
  738. char *
  739. fnstrip(p) char *p; {
  740.     int i, j, k, n, len;
  741.     extern int cmd_quoting;        /* Bad - no externs allowed! */
  742.  
  743.     if (!p)
  744.       return("");
  745.  
  746.     if (*p == '{') {
  747.         len = strlen(p);
  748.         n = 0;
  749.  
  750.         for (j = 0; j < len; j++ ) {
  751.             if (p[j] == '{' &&
  752.         (!cmd_quoting || j == 0 || p[j-1] != CMDQ)) {
  753.                 for (n = 1, i = j+1; i < len; i++ ) {
  754.                     if (p[i] == '{' && (!cmd_quoting || p[i-1] != CMDQ))
  755.               n++;
  756.                     else if (p[i] == '}' && (!cmd_quoting || p[i-1] != CMDQ)) {
  757.                         if (--n == 0) {
  758.                             for (k = j; k < i - 1; k++)
  759.                   p[k] = p[k+1];
  760.                             for (; i < len; i++ )
  761.                   p[i-1] = p[i+1];
  762.                             len -= 2;
  763.                             j = i - 1;
  764.                         }
  765.                     }
  766.                 }
  767.             }
  768.         }
  769.         if (n == 1) { /* Implied right brace at end of field */
  770.             for (k = j; k < len; k++)
  771.           p[k] = p[k+1];
  772.             len -= 1;
  773.         }
  774.     } else if (*p == '"') {
  775.         len = strlen(p);
  776.         n = 0;
  777.  
  778.         for (j = 0; j < len; j++) {
  779.             if (p[j] == '"' &&
  780.         (!cmd_quoting || j == 0 || p[j-1] != CMDQ)) {
  781.                 n++;
  782.  
  783.                 for (i = j + 1; i < len; i++) {
  784.                     if (p[i] == '"' && (!cmd_quoting || p[i-1] != CMDQ)) {
  785.                         n--;
  786.  
  787.                         for (k = j; k < i - 1; k++)
  788.               p[k] = p[k+1];
  789.                         for (; i < len; i++)
  790.               p[i-1] = p[i+1];
  791.                         len -= 2;
  792.                         j = i - 1;
  793.                     }
  794.                 }
  795.             }
  796.         }
  797.         if (n == 1) { /* Implied double quote at end of field */
  798.             for (k = j; k < len; k++ )
  799.           p[k] = p[k+1];
  800.             len -= 1;
  801.         }
  802.     }
  803.     return(p);
  804. }
  805. #endif /* COMMENT */
  806.  
  807. #ifdef COMMENT
  808. /*
  809.   Not used -- Note: these not only write into their arg, but write past
  810.   past the end.
  811. */
  812. char *
  813. brace(fn) char *fn; {
  814.     int spaces = 0;
  815.     char * p, ch, ch2;
  816.     for (p = fn; *p; p++) {
  817.     if (*p == SP) {
  818.         spaces = 1;
  819.         break;
  820.     }
  821.     }
  822.     if (spaces) {
  823.         p = fn;
  824.         ch = *p;
  825.         *p = '{';
  826.         p++;
  827.  
  828.         while (*p) {
  829.             ch2 = *p;
  830.             *p = ch;
  831.             ch = ch2;
  832.             p++;
  833.         }
  834.         *p = ch;
  835.         p++;
  836.         *p = '}';
  837.         p++;
  838.         *p = '\0';
  839.     }
  840.     return(fn);
  841. }
  842. #endif /* COMMENT */
  843.  
  844. /* d q u o t e  --  Puts doublequotes around arg in place. */
  845. /*
  846.    Call with:
  847.      Pointer to buffer and its total length and flag = 0 to use
  848.      doublequotes, 1 to use braces.
  849.    Returns:
  850.      Number: length of result.
  851. */
  852. int
  853. dquote(fn, len, flag) char *fn; int len; int flag; {
  854.     int spaces = 0, k = 0;
  855.     char * p, ch, ch2;
  856.     if (!fn)
  857.       return(0);
  858.  
  859.     k = strlen(fn);
  860.     for (p = fn; *p; p++) {
  861.     if (*p == SP) {
  862.             spaces = 1;
  863.             break;
  864.         }
  865.     }
  866.     if (spaces) {
  867.     if (k + 2 >= len)
  868.       return(k);
  869.         p = fn;
  870.         ch = *p;
  871.         *p = flag ? '{' : '"';
  872.         p++;
  873.  
  874.         while (*p) {
  875.             ch2 = *p;
  876.             *p = ch;
  877.             ch = ch2;
  878.             p++;
  879.         }
  880.         *p = ch;
  881.         p++;
  882.         *p = flag ? '}' : '"';
  883.         p++;
  884.         *p = '\0';
  885.     }
  886.     return(k+2);
  887. }
  888.  
  889.  
  890. /*  M A K E L I S T  ---  Breaks {{s1}{s2}..{sn}} into an array of strings */
  891. /*
  892.   Call with:
  893.     s    = pointer to string to break up.
  894.     list = array of string pointers.
  895.     len  = number of elements in array.
  896.   NOTE: The array must be preinitialized to all NULL pointers.
  897.   If any array element is not NULL, it is assumed to have been malloc'd
  898.   and is therefore freed.  Do NOT call this function with an uninitialized
  899.   array, or with an array that has had any static elements assigned to it.
  900. */
  901. VOID
  902. makelist(s,list,len) char * s; char *list[]; int len; {
  903.     int i, n, q, bc = 0;
  904.     char *p = NULL, *s2 = NULL;
  905.     debug(F110,"makelist s",s,0);
  906.     if (!s) {                /* Check for null or empty string */
  907.     list[0] = NULL;
  908.     return;
  909.     }
  910.     n = strlen(s);
  911.     if (n == 0) {
  912.     list[0] = NULL;
  913.     return;
  914.     }
  915.     if ((s2 = (char *)malloc(n+1))) {    /* Safe copy for poking */
  916.     strcpy(s2,s);            /* (no need for ckstrncpy here) */
  917.     s = s2;
  918.     }
  919.     s = brstrip(s);            /* Strip braces */
  920.     n = strlen(s);            /* Get length */
  921.     if (*s != '{') {            /* Outer braces only */
  922.     if ((p = (char *)malloc(n+1))) { /* So just one pattern */
  923.         strcpy(p,s);        /* (no need for ckstrncpy here) */
  924.         if (list[0])
  925.           free(list[0]);
  926.         list[0] = p;
  927.     }
  928.     if (s2) free(s2);
  929.     return;
  930.     }
  931.     q = 0;                /* Inner ones too */
  932.     i = 0;                /* so a list of patterns. */
  933.     n = 0;
  934.     while (*s && i < len) {
  935.     if (*s == CMDQ) {        /* Quote... */
  936.         q = 1;
  937.         s++;
  938.         n++;
  939.         continue;
  940.     }
  941.     if (*s == '{' && !q) {        /* Opening brace */
  942.         if (bc++ == 0) {        /* Beginning of a group */
  943.         p = ++s;
  944.         n = 0;
  945.         } else {            /* It's a brace inside the group */
  946.         n++;
  947.         s++;
  948.         }
  949.         continue;
  950.     } else if (*s == '}' && !q) {    /* Closing brace */
  951.         if (--bc == 0) {        /* End of a group */
  952.         *s++ = NUL;
  953.         debug(F111,"makelist element",p,i);
  954.         if (list[i])
  955.           free(list[i]);
  956.         if ((list[i] = (char *)malloc(n+1))) {
  957.             ckstrncpy(list[i],p,n+1); /* Note: n+1 */
  958.             i++;
  959.         }
  960.         while (*s == SP) s++;
  961.         p = s;
  962.         n = 0;
  963.         continue;
  964.         } else {            /* Within a group */
  965.         n++;
  966.         s++;
  967.         }
  968.     } else {            /* Regular character */
  969.         q = 0;
  970.         s++;
  971.         n++;
  972.     }
  973.     }
  974.     if (*p && i < len) {        /* Last one */
  975.     if (list[i])
  976.       free(list[i]);
  977.     if ((list[i] = (char *)malloc(n+1))) {
  978.         ckstrncpy(list[i],p,n+1);
  979.         debug(F111,"makelist last element",p,i);
  980.     }
  981.     }
  982.     if (s2) free(s2);
  983. }
  984.  
  985. /*
  986.    M A K E S T R  --  Creates a dynamically allocated string.
  987.  
  988.    Makes a new copy of string s and sets pointer p to its address.
  989.    Handles degenerate cases, like when buffers overlap or are the same,
  990.    one or both arguments are NULL, etc.
  991.  
  992.    The source string is assumed to be NUL-terminated.  Therefore it can not
  993.    be a UCS-2 string or arbitrary binary data.
  994.  
  995.    The target pointer must be either NULL or else a pointer to a previously
  996.    malloc'ed buffer.  If not, expect a core dump or segmentation fault.
  997.  
  998.    Note: The caller can tell whether this routine failed as follows:
  999.  
  1000.      malloc(&p,q);
  1001.      if (q & !p) { makestr() failed };
  1002.  
  1003.    Really this routine should have returned a length, but since it doesn't
  1004.    we set the global variable makestrlen to the length of the result string.
  1005. */
  1006. int makestrlen = 0;
  1007.  
  1008. VOID
  1009. #ifdef CK_ANSIC
  1010. makestr(char **p, const char *s)
  1011. #else
  1012. makestr(p,s) char **p, *s;
  1013. #endif
  1014. /* makestr */ {
  1015.     int x = 0;
  1016.     char *q = NULL;
  1017. #ifdef CK_ANSIC
  1018.     register const char * s2;
  1019. #else
  1020.     register char * s2;
  1021. #endif /* CK_ANSIC */
  1022.     register char * q2;
  1023.  
  1024.     if (*p == s)            /* The two pointers are the same. */
  1025.       return;                /* Don't do anything. */
  1026.  
  1027.     if (!s) {                /* New definition is null? */
  1028.     if (*p)                /* Free old storage. */
  1029.       free(*p);
  1030.     *p = NULL;            /* Return null pointer. */
  1031.     makestrlen = 0;
  1032.     return;
  1033.     }
  1034.     s2 = s;                /* Maybe new string will fit */
  1035.  
  1036. #ifdef COMMENT
  1037. /*
  1038.   This is a fairly big win, allowing us to skip the malloc() and free if the
  1039.   destination string already exists and is not shorter than the source string.
  1040.   But it doesn't allow for possible overlap of source and destination.
  1041. */
  1042.     if (*p) {                /* into old storage... */
  1043.     char * p2 = *p;
  1044.     char c;
  1045.     while (c = *p2) {
  1046.         if (!(*p2++ = *s2++))
  1047.           break;
  1048.         x++;
  1049.     }
  1050.     makestrlen = x;
  1051.     if (c) return;
  1052.     }
  1053. #endif /* COMMENT */
  1054.  
  1055. /* Didn't fit */
  1056.  
  1057.     x = 0;
  1058.     while (*s2++) x++;            /* Get (rest of) length of s.  */
  1059.  
  1060.     if (x >= 0) {            /* Get length, even of empty string. */
  1061.     q = malloc(x+1);        /* Get and point to temp storage. */
  1062.     if (q) {
  1063.         makestrlen = x;        /* Remember length for stats */
  1064.         s2 = s;            /* Point back to beginning of source */
  1065.         q2 = q;            /* Copy dest pointer to increment... */
  1066.         while ((*q2++ = *s2++)) ;    /* Instead of calling strcpy(). */
  1067. /*
  1068.   Note: HP flexelint says that the above loop can result in creation (++) and
  1069.   access (*) of out-of-bounds pointers.  I really don't see it.
  1070. */
  1071.     }
  1072. #ifdef DEBUG
  1073.     else {                /* This would be a really bad error */
  1074.         char tmp[24];        /* So get a good record of it. */
  1075.         if (x > 23) {
  1076.         ckstrncpy(tmp,s,20);
  1077.         strcpy(tmp+20,"...");
  1078.         tmp[23] = NUL;
  1079.         } else {
  1080.         strcpy(tmp,s);        /* We already checked the length */
  1081.         }
  1082.         debug(F110,"MAKESTR MALLOC FAILURE ",tmp,0);
  1083.     }
  1084. #endif /* DEBUG */
  1085.     } else
  1086.       q = NULL;                /* Length of string is zero */
  1087.  
  1088.     if (*p)                /* Now free the original storage. */
  1089.       free(*p);
  1090.     *p = q;
  1091. }
  1092.  
  1093. /*  X M A K E S T R  --  Non-destructive makestr() if s is NULL.  */
  1094.  
  1095. VOID
  1096. #ifdef CK_ANSIC
  1097. xmakestr(char **p, const char *s)
  1098. #else
  1099. xmakestr(p,s) char **p, *s;
  1100. #endif
  1101. /* xmakestr */ {
  1102.     if (s) makestr(p,s);
  1103. }
  1104.  
  1105. #ifndef USE_MEMCPY
  1106. /* C K M E M C P Y  --  Portable (but slow) memcpy() */
  1107.  
  1108. /* Copies n bytes from s to p, allowing for overlap. */
  1109. /* For use when real memcpy() not available. */
  1110.  
  1111. VOID
  1112. ckmemcpy(p,s,n) char *p, *s; int n; {
  1113.     char * q = NULL;
  1114.     register int i;
  1115.     int x;
  1116.  
  1117.     if (!s || !p || n <= 0 || p == s)    /* Verify args */
  1118.       return;
  1119.     x = p - s;                /* Check for overlap */
  1120.     if (x < 0)
  1121.       x = 0 - x;
  1122.     if (x < n) {            /* They overlap */
  1123.     q = p;
  1124.     if (!(p = (char *)malloc(n)))    /* So use a temporary buffer */
  1125.       return;
  1126.     }
  1127.     for (i = 0; i < n; i++)        /* Copy n bytes */
  1128.       p[i] = s[i];
  1129.     if (q) {                /* If we used a temporary buffer */
  1130.     for (i = 0; i < n; i++)        /* copy from it to destination */
  1131.       q[i] = p[i];
  1132.     if (p) free(p);            /* and free the temporary buffer */
  1133.     }
  1134. }
  1135. #endif /* USE_MEMCPY */
  1136.  
  1137.  
  1138. /*  C K S T R C M P  --  String comparison with case-matters selection */
  1139. /*
  1140.   Call with pointers to the two strings, s1 and s2, a length, n,
  1141.   and c == 0 for caseless comparison, nonzero for case matters.
  1142.   Call with n == -1 to compare without a length limit.
  1143.   Compares up to n characters of the two strings and returns:
  1144.     1 if s1 > s2
  1145.     0 if s1 = s2
  1146.    -1 if s1 < s2
  1147.   Note: case handling is only as good as isupper() and tolower().
  1148. */
  1149. int
  1150. ckstrcmp(s1,s2,n,c) char *s1, *s2; register int n, c; {
  1151.     register CHAR t1, t2;
  1152.     if (n == 0) return(0);
  1153.     if (!s1) s1 = "";            /* Watch out for null pointers. */
  1154.     if (!s2) s2 = "";
  1155.     if (!*s1) return(*s2 ? -1 : 0);
  1156.     if (!*s2) return(1);
  1157.     while (n--) {
  1158.     t1 = (CHAR) *s1++;        /* Get next character from each. */
  1159.     t2 = (CHAR) *s2++;
  1160.     if (!t1) return(t2 ? -1 : 0);
  1161.     if (!t2) return(1);
  1162.     if (!c) {            /* If case doesn't matter */
  1163.         if (isupper(t1)) t1 = tolower(t1); /* Convert case. */
  1164.         if (isupper(t2)) t2 = tolower(t2);
  1165.     }
  1166.     if (t1 < t2) return(-1);    /* s1 < s2 */
  1167.     if (t1 > t2) return(1);        /* s1 > s2 */
  1168.     }
  1169.     return(0);                /* They're equal */
  1170. }
  1171.  
  1172. /*  C K S T R P R E  --  Caseless string prefix comparison  */
  1173.  
  1174. /* Returns position of the first char in the 2 strings that doesn't match */
  1175.  
  1176. int
  1177. ckstrpre(s1,s2) char *s1, *s2; {
  1178.     CHAR t1, t2;
  1179.     int n = 0;
  1180.     if (!s1) s1 = "";
  1181.     if (!s2) s2 = "";
  1182.     while (1) {
  1183.     t1 = (CHAR) *s1++;
  1184.     t2 = (CHAR) *s2++;
  1185.     if (!t1 || !t2) return(n);
  1186.     if (isupper(t1)) t1 = tolower(t1);
  1187.     if (isupper(t2)) t2 = tolower(t2);
  1188.     if (t1 != t2)
  1189.       return(n);
  1190.     n++;
  1191.     }
  1192. }
  1193.  
  1194. #define GLOBBING
  1195.  
  1196. /*  C K M A T C H  --  Match a string against a pattern  */
  1197. /*
  1198.   Call with:
  1199.     pattern to be matched.
  1200.     string to look for the pattern in.
  1201.     icase is 1 if case-sensitive, 0 otherwise.
  1202.     opts is a bitmask:
  1203.       Bit 0 (=1):
  1204.     1 = Match strings starting with '.'
  1205.     0 = Don't match them (used with UNIX filenames).
  1206.       Bit 1 (=2):
  1207.     1 = File globbing (dirseps are fences);
  1208.     0 = Dirseps are not fences.
  1209.       Bit 2 (=4):
  1210.     1 = Allow ^ and $ anchors at beginning and end of pattern.
  1211.     0 = Don't allow them (normal case for filename matching).
  1212.       Bit 3 (and beyond): Undefined.
  1213.   Works only with NUL-terminated strings.
  1214.   Pattern may contain any number of ? and/or *.
  1215.   If CKREGEX is defined, also [abc], [a-z], and/or {string,string,...}.
  1216.   (Note: REGEX is a misnomer, see below.)
  1217.  
  1218.   Returns:
  1219.     0 if string does not match pattern,
  1220.     >= 1, the 1-based position in the string where the match was found.
  1221.  
  1222.   To be done:
  1223.     Find a way to identify the piece of the string that matched the pattern,
  1224.     as in Snobol "LINE (PAT . RESULT)".  This is now partially done by
  1225.     setting matchpos and matchend (except matchend needs some tuning).  But
  1226.     these are useless unless a copy of the string is kept, or a copy of the
  1227.     matching part is made.  But that would be too costly in performance --
  1228.     this routine has to be fast because it's used for wildcard expansion.
  1229.  
  1230.   Note:
  1231.     Patterns are not the same as regular expressions, in which '*' means
  1232.     0 or more repetitions of the preceding item.  For example "a*b" as a
  1233.     pattern matches any string that starts with 'a' and ends with 'b'; as a
  1234.     regular expression it matches any string of zero or more a's followed by
  1235.     one b.  Regular expressions are especially useful in matching strings of
  1236.     (say) digits, or letters, e.g. "[0-9]*" matches any string of digits.
  1237. */
  1238. static char * mypat = NULL;        /* For rewriting pattern */
  1239. static int matchpos = 0;
  1240. int matchend = 0;
  1241. static int matchdepth = 0;
  1242. static int stringpos = 0;
  1243. static char * ostring = NULL;
  1244.  
  1245. #define MATCHRETURN(x,y) { rc=y; where=x; goto xckmatch; }
  1246. static char * lastpat = NULL;
  1247.  
  1248. int
  1249. ckmatch(pattern, string, icase, opts) char *pattern,*string; int icase, opts; {
  1250.     int q = 0, i = 0, k = -1, x, flag = 0;
  1251.     int rc = 0;                /* Return code */
  1252.     int where = -1;
  1253.     CHAR cp;                /* Current character from pattern */
  1254.     CHAR cs;                /* Current character from string */
  1255.     int plen, dot, globbing, xstar = 0;
  1256.  
  1257.     debug(F111,"CKMATCH ENTRY pat opt",pattern,opts);
  1258.     debug(F111,"CKMATCH ENTRY str dep",string,matchdepth);
  1259.  
  1260.     globbing = opts & 2;
  1261.  
  1262.     if (!string) string = "";
  1263.     if (!pattern) pattern = "";
  1264.     if (!*pattern) {            /* Empty pattern matches anything */
  1265.     matchdepth++;            /* (it wasn't incremented yet) */
  1266.     MATCHRETURN(0,1);
  1267.     }
  1268.     if (matchdepth == 0) {        /* Top-level call? */
  1269.     stringpos = 0;            /* Reset indices etc. */
  1270.     matchpos = 0;
  1271.     matchend = 0;
  1272.     ostring = string;
  1273.     lastpat = pattern;
  1274.     dot = opts & 1;
  1275.     plen = strlen(pattern);        /* Length of pattern */
  1276. /* This would be used in calculating length of matching segment */
  1277.     if (plen > 0)            /* User's pattern ends with '*' */
  1278.       if (pattern[plen - 1] == '*')
  1279.         xstar = 1;
  1280.     if (pattern[0] == '*') {    /* User's pattern starts with '*' */
  1281.         matchpos = 1;
  1282.         debug(F111,"CKMATCH 1",string, matchpos);
  1283.     }
  1284.     if (opts & 4) {            /* ^..$ allowed (top level only) */
  1285.         /* Rewrite pattern to account for ^..$ anchoring... */
  1286.  
  1287.         if (mypat) free(mypat);    /* Get space for "*pattern*" */
  1288.         mypat = (char *)malloc(plen + 4);
  1289.         if (mypat) {        /* Got space? */
  1290.         char * s = pattern, * p = mypat; /* Set working pointers */
  1291.         if (*s == '^') {    /* First source char is ^ */
  1292.             s++;        /* so skip past it */
  1293.         } else if (*s != '*') {    /* otherwise */
  1294.             *p++ = '*';        /* prepend '*' to pattern */
  1295.         }
  1296.         while (*s) {        /* Copy rest of pattern */
  1297.             if (!*(s+1)) {    /* Final pattern character? */
  1298.             if (*s != '$') { /* If it's not '$' */
  1299.                 *p++ = *s;    /* Copy it into the pattern */
  1300.                 if (*s++ != '*') /* And if it's also not '*' */
  1301.                   *p++ = '*'; /* append '*'. */
  1302.             }
  1303.             break;        /* Done */
  1304.             } else        /* Not final character */
  1305.               *p++ = *s++;    /* Just copy it */
  1306.         }
  1307.         *p = NUL;        /* Terminate the new pattern */
  1308.         pattern = mypat;    /* Make the switch */
  1309.         }
  1310.         debug(F110,"CKMATCH INIT pat",pattern,0);
  1311.     }
  1312.     }
  1313.     matchdepth++;            /* Now increment call depth */
  1314.  
  1315. #ifdef UNIX
  1316.     if (!dot) {                /* For UNIX file globbing */
  1317.     if (*string == '.' && *pattern != '.' && !matchdot) {
  1318.         if (
  1319. #ifdef CKREGEX
  1320.         *pattern != '{' && *pattern != '['
  1321. #else
  1322.         1
  1323. #endif /* CKREGEX */
  1324.         ) {
  1325.         debug(F110,"ckmatch skip",string,0);
  1326.         MATCHRETURN(1,0);
  1327.         }
  1328.     }
  1329.     }
  1330. #endif /* UNIX */
  1331.     while (1) {
  1332.     k++;
  1333.     cp = *pattern;            /* Character from pattern */
  1334.     cs = *string;            /* Character from string */
  1335.  
  1336. #ifdef COMMENT
  1337.     debug(F000,"CKMATCH pat cp",pattern,cp);
  1338.     debug(F000,"CKMATCH str cs",string,cs);
  1339. #endif /* COMMENT */
  1340.  
  1341.     if (!cs) {            /* End of string - done. */
  1342.         x = (!cp || (cp == '*' && !*(pattern+1))) ? 1 : 0;
  1343.         if (x) {
  1344.         if (!matchpos) {
  1345.             matchpos = stringpos;
  1346.             debug(F111,"CKMATCH A",string, matchpos);
  1347.         }
  1348.         matchend = stringpos;
  1349.         MATCHRETURN(2,matchpos);
  1350.         }
  1351.         debug(F111,"CKMATCH ZERO d",string, matchpos);
  1352.         matchpos = 0;
  1353.         MATCHRETURN(16,matchpos);
  1354.     }
  1355.         if (!icase) {            /* If ignoring case */
  1356.         if (isupper(cp))        /* convert both to lowercase. */
  1357.           cp = tolower(cp);
  1358.         if (isupper(cs))
  1359.           cs = tolower(cs);
  1360.         }
  1361.     if (q) {            /* This character was quoted */
  1362.         debug(F000,"CKMATCH QUOTED",pattern,cp);
  1363.         q = 0;            /* Turn off quote flag */
  1364.  
  1365.         if (cs == cp) {        /* Compare directly */
  1366.         if (!matchpos) {    /* Matches */
  1367.             matchpos = stringpos;
  1368.             debug(F111,"CKMATCH \\ new match",string, matchpos);
  1369.         }
  1370.         pattern++;
  1371.         } else {            /* Doesn't match */
  1372.         pattern = lastpat;    /* Back up the pattern */
  1373.         matchpos = 0;
  1374.         debug(F111,"CKMATCH \\ no match",pattern, matchpos);
  1375.         }
  1376.         string++;
  1377.         stringpos++;
  1378.         continue;
  1379.     }
  1380.     if (cp == CMDQ && !q) {        /* Quote in pattern */
  1381.         debug(F000,"CKMATCH QUOTE",pattern,cp);
  1382.         q = 1;            /* Set flag */
  1383.         pattern++;            /* Advance to next pattern character */
  1384.         continue;            /* and continue. */
  1385.     }
  1386.     if (cs && cp == '?') {        /* '?' matches any char */
  1387.         if (!matchpos) {
  1388.         matchpos = stringpos;
  1389.         debug(F111,"CKMATCH D",string, matchpos);
  1390.         }
  1391.         debug(F110,"CKMATCH ? pat",pattern,0);
  1392.         debug(F110,"CKMATCH ? str",string,0);
  1393.         pattern++, string++;
  1394.         stringpos++;
  1395.         continue;
  1396. #ifdef CKREGEX
  1397.     } else if (cp == '[') {        /* Have bracket */
  1398.         int q = 0;            /* My own private q */
  1399.         char * psave = NULL;    /* and backup pointer */
  1400.         CHAR clist[256];        /* Character list from brackets */
  1401.         CHAR c, c1, c2;
  1402.         for (i = 0; i < 256; i++)    /* memset() etc not portable */
  1403.           clist[i] = NUL;
  1404.         psave = ++pattern;        /* Where pattern starts */
  1405.         debug(F111,"CKMATCH [] ",pattern-1, matchpos);
  1406.         for (flag = 0; !flag; pattern++) { /* Loop thru pattern */
  1407.         c = (CHAR)*pattern;    /* Current char */
  1408.         if (q) {        /* Quote within brackets */
  1409.             q = 0;
  1410.             clist[c] = 1;
  1411.             continue;
  1412.         }
  1413.         if (!icase)        /* Case conversion */
  1414.           if (isupper(c))
  1415.             c = tolower(c);
  1416.         switch (c) {        /* Handle unquoted character */
  1417.           case NUL:        /* End of string */
  1418.             MATCHRETURN(4,0);    /* No matching ']' so fail */
  1419.           case CMDQ:        /* Next char is quoted */
  1420.             q = 1;        /* Set flag */
  1421.             continue;        /* and continue. */
  1422.           case '-':        /* A range is specified */
  1423.             c1 = (pattern > psave) ? (CHAR)*(pattern-1) : NUL;
  1424.             c2 = (CHAR)*(pattern+1); /* IGNORE OUT-OF-BOUNDS WARNING */
  1425.             if (c2 == ']') c2 = NUL; /* (it can't happen) */
  1426.             if (c1 == NUL) c1 = c2;
  1427.             for (c = c1; c <= c2; c++) {
  1428.             clist[c] = 1;
  1429.             if (!icase) {
  1430.                 if (islower(c)) {
  1431.                 clist[toupper(c)] = 1;
  1432.                 } else if (isupper(c)) {
  1433.                 clist[tolower(c)] = 1;
  1434.                 }
  1435.             }
  1436.             }
  1437.             continue;
  1438.           case ']':        /* End of bracketed sequence */
  1439.             flag = 1;        /* Done with FOR loop */
  1440.             break;        /* Compare what we have */
  1441.           default:        /* Just a char */
  1442.             clist[c] = 1;    /* Record it */
  1443.             if (!icase) {
  1444.             if (islower(c)) {
  1445.                 clist[toupper(c)] = 1;
  1446.             } else if (isupper(c)) {
  1447.                 clist[tolower(c)] = 1;
  1448.             }
  1449.             }
  1450.             continue;
  1451.         }
  1452.         }
  1453.         if (!clist[(unsigned)cs]) {    /* Match? */
  1454.         MATCHRETURN(5,0);    /* Nope, done. */
  1455.         }
  1456.         if (!matchpos) {
  1457.         matchpos = stringpos;
  1458.         debug(F111,"CKMATCH [] match",string, matchpos);
  1459.         }
  1460.         string++;            /* Yes, advance string pointer */
  1461.         stringpos++;
  1462.         continue;            /* and go on. */
  1463.     } else if (cp == '{') {        /* Braces enclosing list of strings */
  1464.         char * p, * s, * s2, * buf = NULL;
  1465.         int n, bc = 0;
  1466.         int len = 0;
  1467.         debug(F111,"CKMATCH {} ",string, matchpos);
  1468.         for (p = pattern++; *p; p++) {
  1469.         if (*p == '{') bc++;
  1470.         if (*p == '}') bc--;
  1471.         if (bc < 1) break;
  1472.         }
  1473.         if (bc != 0) {        /* Braces don't match */
  1474.         MATCHRETURN(6,0);    /* Fail */
  1475.         } else {            /* Braces do match */
  1476.         int q = 0, done = 0;
  1477.         len = *p ? strlen(p+1) : 0; /* Length of rest of pattern */
  1478.         n = p - pattern;        /* Size of list in braces */
  1479.         if ((buf = (char *)malloc(n+1))) { /* Copy so we can poke it */
  1480.             char * tp = NULL;
  1481.             int k, sofar;
  1482.             ckstrncpy(buf,pattern,n+1);
  1483.             sofar = string - ostring - matchpos + 1;
  1484.             if (sofar < 0) sofar = 0;
  1485.             debug(F111,"CKMATCH .. string",string,sofar);
  1486.             debug(F111,"CKMATCH .. ostring",ostring,sofar);
  1487.             n = 0;
  1488.             for (s = s2 = buf; 1; s++) { /* Loop through segments */
  1489.             n++;
  1490.             if (q) {    /* This char is quoted */
  1491.                 q = 0;
  1492.                 if (!*s)
  1493.                   done = 1;
  1494.                 continue;
  1495.             }
  1496.             if (*s == CMDQ && !q) {    /* Quote next char */
  1497.                 q = 1;
  1498.                 continue;
  1499.             }
  1500.             if (!*s || *s == ',') {    /* End of this segment */
  1501.                 int tplen = 0;
  1502.                 if (!*s)    /* If end of buffer */
  1503.                   done = 1;    /* then end of last segment */
  1504.                 *s = NUL;    /* Overwrite comma with NUL */
  1505.                 debug(F111,"CKMATCH {} segment",s2,done);
  1506.                 tplen = n + len + sofar + 2;
  1507.                 if (!*s2) {    /* Empty segment, no advancement */
  1508.                 k = 0;
  1509.                 } else if ((tp = (char *)malloc(tplen))) {
  1510.                 int savpos;
  1511.                 debug(F111,"CKMATCH {} ostring sofar",
  1512.                       &ostring[matchpos-1],
  1513.                       sofar);
  1514.                 tp[0] = '*';
  1515.                 ckstrncpy(&tp[1],&ostring[matchpos-1],sofar+1);
  1516.                 ckstrncat(tp,s2,tplen); /* Current segment */
  1517.                 ckstrncat(tp,p+1,tplen); /* rest of pattern */
  1518.  
  1519.                 debug(F101,"CKMATCH {} matchpos","",matchpos);
  1520.                 savpos = matchpos;
  1521.                 matchpos = 0;
  1522. #ifdef DEBUG
  1523.                 if (deblog) {
  1524.                     debug(F111,"CKMATCH {} tp",tp,matchpos);
  1525.                     debug(F111,"CKMATCH {} string",
  1526.                       string,matchpos);
  1527.                     debug(F111,"CKMATCH {} ostring",
  1528.                       ostring,savpos);
  1529.                 }
  1530. #endif /* DEBUG */
  1531.                 k = ckmatch(tp,
  1532.                         (string > ostring) ?
  1533.                         &ostring[savpos-1] : string,
  1534.                         icase,opts);
  1535. #ifdef DEBUG
  1536.                 if (deblog) {
  1537.                     debug(F101,"CKMATCH {} k","",k);
  1538.                     debug(F101,"CKMATCH {} savpos","",savpos);
  1539.                 }
  1540. #endif /* DEBUG */
  1541.                 free(tp);
  1542.                 tp = NULL;
  1543.                 if (k == 0) {
  1544.                     matchpos = savpos;
  1545.                 }
  1546.                 if (k > 0) { /* If it matched we're done */
  1547.                     MATCHRETURN(7,k);
  1548.                 }
  1549.                 } else {    /* Malloc failure */
  1550.                 MATCHRETURN(14,0);
  1551.                 }
  1552.                 if (k) {    /* Successful comparison */
  1553.                 if (!matchpos) {
  1554.                     matchpos = stringpos;
  1555.                     debug(F111,"CKMATCH {} match",
  1556.                       string, matchpos);
  1557.                 }
  1558.                 string += n-1; /* Advance pointers */
  1559.                 pattern = p+1;
  1560.                 break;
  1561.                 }
  1562.                 if (done)    /* If no more segments */
  1563.                   break;    /* break out of segment loop. */
  1564.                 s2 = s+1;    /* Otherwise, on to next segment */
  1565.                 n = 0;
  1566.             }
  1567.             }
  1568.             free(buf);
  1569.         }
  1570.         }
  1571. #endif /* CKREGEX */
  1572.     } else if (cp == '*') {        /* Pattern char is asterisk */
  1573.         char * psave;
  1574.         char * p, * s = NULL;    /* meaning match anything */
  1575.         int k, n, q = 0;
  1576.         while (*pattern == '*')    /* Collapse successive asterisks */
  1577.           pattern++;
  1578.         psave = pattern;        /* First non-asterisk after asterisk */
  1579.         lastpat = pattern - 1;    /* Ditto, global */
  1580.         debug(F111,"CKMATCH * ",string,matchpos);
  1581.         for (n = 0, p = psave; *p; p++,n++) { /* Find next meta char */
  1582.         if (!q) {
  1583.             if (*p == '?' || *p == '*' || *p == CMDQ
  1584. #ifdef CKREGEX
  1585.             || *p == '[' || *p == '{'
  1586. #endif /* CKREGEX */
  1587.             )
  1588.               break;
  1589. #ifdef GLOBBING
  1590.             if (globbing
  1591. #ifdef UNIXOROSK
  1592.             && *p == '/'
  1593. #else
  1594. #ifdef VMS
  1595.             && (*p == '.' || *p == ']' ||
  1596.                 *p == '<' || *p == '>' ||
  1597.                 *p == ':' || *p == ';')
  1598. #else
  1599. #ifdef datageneral
  1600.             && *p == ':'
  1601. #else
  1602. #ifdef STRATUS
  1603.             && *p == '>'
  1604. #endif /* STRATUS */
  1605. #endif /* datageneral */
  1606. #endif /* VMS */
  1607. #endif /* UNIXOROSK */
  1608.             )
  1609.               break;
  1610. #endif /* GLOBBING */
  1611.         }
  1612.         }
  1613.         debug(F111,"CKMATCH * n string",string,n);
  1614.         debug(F111,"CKMATCH * n pattrn",pattern,n);
  1615.         debug(F111,"CKMATCH * n p",p,n);
  1616.         if (n > 0) {        /* Literal string to match  */
  1617.         s = (char *)malloc(n+1);
  1618.         if (s) {
  1619.             ckstrncpy(s,psave,n+1); /* Copy cuz no poking original */
  1620.             if (*p) {
  1621.             k = ckindex(s,string,0,0,icase); /* 1-based index() */
  1622.             debug(F110,"CKMATCH * Index() string",string,0);
  1623.             debug(F110,"CKMATCH * Index() pattrn",s,0);
  1624.             debug(F101,"CKMATCH * Index() result","",k);
  1625.             } else {        /* String is right-anchored */
  1626.             k = ckindex(s,string,-1,1,icase); /* rindex() */
  1627.             debug(F111,"CKMATCH * Rindex()",string,k);
  1628.             debug(F110,"CKMATCH * Rindex() pattrn",s,0);
  1629.             debug(F101,"CKMATCH * Rindex() result","",k);
  1630.             }
  1631.             free(s);
  1632.             if (k < 1) {
  1633.             MATCHRETURN(8,0);
  1634.             }
  1635.             debug(F111,"CKMATCH * stringpos matchpos",
  1636.               ckitoa(stringpos), matchpos);
  1637.             if (!matchpos) {
  1638.             matchpos = string - ostring + k;
  1639.             debug(F111,"CKMATCH * new match ", string, matchpos);
  1640.             }
  1641.             string += k + n - 1;
  1642.             stringpos += k + n - 1;
  1643.             pattern += n;
  1644.             debug(F111,"CKMATCH * new string", string, stringpos);
  1645.             debug(F110,"CKMATCH * new pattrn", pattern, 0);
  1646.             continue;
  1647.         }
  1648.         } else if (!*p) {        /* Asterisk at end matches the rest */
  1649.         if (!globbing) {    /* (if not filename globbing) */
  1650.             if (!matchpos) {
  1651.             matchpos = stringpos;
  1652.             debug(F111,"CKMATCH *$ ",string, matchpos);
  1653.             }
  1654.             matchend = stringpos;
  1655.             MATCHRETURN(9,matchpos);
  1656.         }
  1657. #ifdef GLOBBING
  1658.         while (*string) {
  1659.             if (globbing    /* Filespec so don't cross fields */
  1660. #ifdef OS2
  1661.             && *string == '/' || *string == '\\' ||
  1662.             *string == ':'
  1663. #else
  1664. #ifdef UNIXOROSK
  1665.             && *string == '/'
  1666. #else
  1667. #ifdef VMS
  1668.             && (*string == '.' || *string == ']' ||
  1669.                 *string == '<' || *string == '>' ||
  1670.                 *string == ':' || *string == ';')
  1671. #else
  1672. #ifdef datageneral
  1673.             && *string == ':'
  1674. #else
  1675. #ifdef STRATUS
  1676.             && *string == '>'
  1677. #else
  1678.             && *string == '/' /* (catch-all) */
  1679. #endif /* STRATUS */
  1680. #endif /* datageneral */
  1681. #endif /* VMS */
  1682. #endif /* UNIXOROSK */
  1683. #endif /* OS2 */
  1684.             ) {
  1685.             matchend = stringpos;
  1686.             MATCHRETURN(10,0);
  1687.             }
  1688.             if (!matchpos) {
  1689.             matchpos = stringpos;
  1690.             debug(F111,"CKMATCH *$ match",string, matchpos);
  1691.             }
  1692.             string++;
  1693.             stringpos++;
  1694.         }
  1695. #endif /* GLOBBING */
  1696.         if (!matchpos) {
  1697.             matchpos = stringpos;
  1698.             debug(F111,"CKMATCH ** match",string, matchpos);
  1699.         }
  1700.         matchend = stringpos;
  1701.         MATCHRETURN(11,matchpos);
  1702.  
  1703.         } else {            /* A meta char follows asterisk */
  1704.         if (!*string)
  1705.           MATCHRETURN(17, matchpos = 0);
  1706.         while (*string && (k = ckmatch(p,string,icase,opts) < 1)) {
  1707.             string++;
  1708.             stringpos++;
  1709.         }
  1710.         debug(F111,"CKMATCH *<meta> k",string, k);
  1711.         if (!matchpos && k > 0) {
  1712.             matchpos = stringpos;
  1713.             debug(F111,"CKMATCH *<meta>",string, matchpos);
  1714.         }
  1715.         MATCHRETURN(12, (*string) ? matchpos : 0);
  1716.         }
  1717.     } else if (cs == cp) {
  1718.         pattern++, string++;
  1719.         stringpos++;
  1720.         if (!matchpos) {
  1721.         matchpos = stringpos;
  1722.         debug(F111,"CKMATCH cs=cp",string, matchpos);
  1723.         }
  1724.         continue;
  1725.     } else {
  1726.         MATCHRETURN(13,0);
  1727.     }
  1728.     }
  1729.   xckmatch:
  1730.     {
  1731. #ifdef DEBUG
  1732.     char msgbuf[96];
  1733. #endif /* DEBUG */
  1734.     if (matchdepth > 0)
  1735.       matchdepth--;
  1736.     matchpos = rc;
  1737. #ifdef DEBUG
  1738.     ckmakxmsg(msgbuf,96,
  1739.           "CKMATCH RETURN[",
  1740.           ckitoa(where),
  1741.           "] matchpos=",
  1742.           ckitoa(matchpos),
  1743.           " matchdepth=",
  1744.           ckitoa(matchdepth),
  1745.           " string=",NULL,NULL,NULL,NULL,NULL
  1746.           );
  1747.     debug(F110,msgbuf,string,0);
  1748. #endif /* DEBUG */
  1749.     return(rc);
  1750.     }
  1751. }
  1752.  
  1753.  
  1754. #ifdef CKFLOAT
  1755. /*  I S F L O A T  -- Verify that arg represents a floating-point number */
  1756.  
  1757. /*
  1758.   Portable replacement for atof(), strtod(), scanf(), etc.
  1759.  
  1760.   Call with:
  1761.     s = pointer to string
  1762.     flag == 0 means entire string must be a (floating-pointing) number.
  1763.     flag != 0 means to terminate scan on first character that is not legal.
  1764.  
  1765.   Returns:
  1766.     1 if result is a legal number;
  1767.     2 if result has a fractional part;
  1768.     0 if not or if string empty.
  1769.  
  1770.   Side effect:
  1771.     Sets global floatval to floating-point value if successful.
  1772.  
  1773.   Number need not contain a decimal point -- integer is subcase of float.
  1774.   Scientific notation not supported.
  1775. */
  1776. CKFLOAT floatval = 0.0;            /* For returning value */
  1777.  
  1778. int
  1779. isfloat(s,flag) char *s; int flag; {
  1780.     int state = 0;
  1781.     int sign = 0;
  1782.     char c;
  1783.     CKFLOAT d = 0.0, f = 0.0;
  1784.  
  1785.     if (!s) return(0);
  1786.     if (!*s) return(0);
  1787.  
  1788.     while (isspace(*s)) s++;
  1789.  
  1790.     if (*s == '-') {            /* Handle optional sign */
  1791.     sign = 1;
  1792.     s++;
  1793.     } else if (*s == '+')
  1794.       s++;
  1795.     while ((c = *s++)) {        /* Handle numeric part */
  1796.     switch (state) {
  1797.       case 0:            /* Mantissa... */
  1798.         if (isdigit(c)) {
  1799.         f = f * 10.0 + (CKFLOAT)(c - '0');
  1800.         continue;
  1801.         } else if (c == '.') {
  1802.         state = 1;
  1803.         d = 1.0;
  1804.         continue;
  1805.         }
  1806.         if (flag)            /* Not digit or period */
  1807.           goto done;        /* break if flag != 0 */
  1808.         return(0);            /* otherwise fail. */
  1809.       case 1:            /* Fraction... */
  1810.         if (isdigit(c)) {
  1811.         d *= 10.0;
  1812.         f += (CKFLOAT)(c - '0') / d;
  1813.         continue;
  1814.         }
  1815.       default:
  1816.         if (flag)            /* Illegal character */
  1817.           goto done;        /* Break */
  1818.         return(0);            /* or fail, depending on flag */
  1819.     }
  1820.     }
  1821.   done:
  1822.     if (sign) f = 0.0 - f;        /* Apply sign to result */
  1823.     floatval = f;            /* Set result */
  1824.     return(d ? 2 : 1);            /* Succeed */
  1825. }
  1826. #endif /* CKFLOAT */
  1827.  
  1828. /* Sorting routines... */
  1829.  
  1830. /* S H _ S O R T  --  Shell sort -- sorts string array s in place. */
  1831.  
  1832. /*
  1833.   Highly defensive and relatively quick.
  1834.   Uses shell sort algorithm.
  1835.  
  1836.   Args:
  1837.    s = pointer to array of strings.
  1838.    p = pointer to a second array to sort in parallel s, or NULL for none.
  1839.    n = number of elements in s.
  1840.    k = position of key.
  1841.    r = ascending lexical order if zero, reverse lexical order if nonzero.
  1842.    c = 0 for case independence, 1 for case matters, 2 for numeric.
  1843.  
  1844.   If k is past the right end of a string, the string is considered empty
  1845.   for comparison purposes.
  1846.  
  1847.   Hint:
  1848.    To sort a piece of an array, call with s pointing to the first element
  1849.    and n the number of elements to sort.
  1850.  
  1851.   Return value:
  1852.    None.  Always succeeds, unless any of s[0]..s[n-1] are bad pointers,
  1853.    in which case memory violations are possible, but C offers no defense
  1854.    against this, so no way to gracefully return an error code.
  1855. */
  1856. VOID
  1857. sh_sort(s,p,n,k,r,c) char **s, **p; int n, k, r, c; {
  1858.     int m, i, j, x;
  1859.     char *t, *t1, *t2, *u = NULL;
  1860. #ifdef CKFLOAT
  1861.     CKFLOAT f1, f2;
  1862. #else
  1863.     long n1, n2;
  1864. #endif /* CKFLOAT */
  1865.  
  1866.     if (!s) return;            /* Nothing to sort? */
  1867.     if (n < 2) return;            /* Not enough elements to sort? */
  1868.     if (k < 0) k = 0;            /* Key */
  1869.  
  1870.     m = n;                /* Initial group size is whole array */
  1871.     while (1) {
  1872.     m = m / 2;            /* Divide group size in half */
  1873.     if (m < 1)            /* Small as can be, so done */
  1874.       break;
  1875.     for (j = 0; j < n-m; j++) {    /* Sort each group */
  1876.         t = t2 = s[j+m];        /* Compare this one... */
  1877.         if (!t)            /* But if it's NULL */
  1878.           t2 = "";            /* make it the empty string */
  1879.         if (p)            /* Handle parallel array, if any */
  1880.           u = p[j+m];
  1881.         if (k > 0 && *t2) {
  1882.         if ((int)strlen(t2) < k) /* If key too big */
  1883.           t2 = "";        /* make key the empty string */
  1884.         else            /* Key is in string */
  1885.           t2 = t + k;        /* so point to key position */
  1886.         }
  1887.         for (i = j; i >= 0; i -= m) { /* Loop thru comparands s[i..]*/
  1888.         t1 = s[i];
  1889.         if (!t1)        /* Same deal */
  1890.           t1 = "";
  1891.         if (k > 0 && *t1) {
  1892.             if ((int)strlen(t1) < k)
  1893.               t1 = "";
  1894.             else
  1895.               t1 = s[i]+k;
  1896.         }
  1897.         if (c == 2) {        /* Numeric comparison */
  1898.             x = 0;
  1899. #ifdef CKFLOAT
  1900.             f2 = 0.0;
  1901.             f1 = 0.0;
  1902.             if (isfloat(t1,1)) {
  1903.             f1 = floatval;
  1904.             if (isfloat(t2,1))
  1905.               f2 = floatval;
  1906.             else
  1907.               f1 = 0.0;
  1908.             }
  1909.             if (f2 < f1)
  1910.               x = 1;
  1911.             else
  1912.               x = -1;
  1913. #else
  1914.             n2 = 0L;
  1915.             n1 = 0L;
  1916.             if (rdigits(t1)) {
  1917.             n1 = atol(t1);
  1918.             if (rdigits(t2))
  1919.               n2 = atol(t2);
  1920.             else
  1921.               n1 = 0L;
  1922.             }
  1923.             if (n2 < n1)
  1924.               x = 1;
  1925.             else
  1926.               x = -1;
  1927. #endif /* CKFLOAT */
  1928.         } else {
  1929.             x = ckstrcmp(t1,t2,-1,c); /* Compare */
  1930.         }
  1931.         if (r == 0 && x < 0)
  1932.           break;
  1933.         if (r != 0 && x > 0)
  1934.           break;
  1935.         s[i+m] = s[i];
  1936.         if (p) p[i+m] = p[i];
  1937.         }
  1938.         s[i+m] = t;
  1939.         if (p) p[i+m] = u;
  1940.     }
  1941.     }
  1942. }
  1943.  
  1944.  
  1945. /* C K R A D I X  --  Radix converter */
  1946. /*
  1947.    Call with:
  1948.      s:   a number in string format.
  1949.      in:  int, specifying the radix of s, 2-36.
  1950.      out: int, specifying the radix to convert to, 2-36.
  1951.    Returns:
  1952.      NULL on error (illegal radix, illegal number, etc.).
  1953.      "-1" on overflow (number too big for unsigned long).
  1954.      Otherwise: Pointer to result.
  1955. */
  1956. char *
  1957. ckradix(s,in,out) char * s; int in, out; {
  1958.     char c, *r = rxresult;
  1959.     int d, minus = 0;
  1960.     unsigned long zz = 0L;
  1961.     long z = 0L;
  1962.     if (in < 2 || in > 36)        /* Verify legal input radix */
  1963.       return(NULL);
  1964.     if (out < 2 || out > 36)        /* and output radix. */
  1965.       return(NULL);
  1966.     if (*s == '+') {            /* Get sign if any */
  1967.     s++;
  1968.     } else if (*s == '-') {
  1969.     minus++;
  1970.     s++;
  1971.     }
  1972.     while (*s == SP || *s == '0')    /* Trim leading blanks or 0's */
  1973.       s++;
  1974. /*
  1975.   For detecting overflow, we use a signed copy of the unsigned long
  1976.   accumulator.  If it goes negative, we know we'll overflow NEXT time
  1977.   through the loop.
  1978. */
  1979.     for (; *s;  s++) {            /* Convert from input radix to */
  1980.     c = *s;                /* unsigned long */
  1981.     if (islower(c)) c = toupper(c);
  1982.     if (c >= '0' && c <= '9')
  1983.       d = c - '0';
  1984.     else if (c >= 'A' && c <= 'Z')
  1985.       d = c - 'A' + 10;
  1986.     else
  1987.       return(NULL);
  1988.     if (d >= in)            /* Check for illegal digit */
  1989.       return(NULL);
  1990.     zz = zz * in + d;
  1991.     if (z < 0L)            /* Clever(?) overflow detector */
  1992.       return("-1");
  1993.         z = zz;
  1994.     }
  1995.     if (!zz) return("0");
  1996.     r = &rxresult[RXRESULT];        /* Convert from unsigned long */
  1997.     *r-- = NUL;                /* to output radix. */
  1998.     while (zz > 0 && r > rxresult) {
  1999.     d = zz % (unsigned)out;
  2000.     *r-- = rxdigits[d];
  2001.     zz = zz / (unsigned)out;
  2002.     }
  2003.     if (minus) *r-- = '-';        /* Replace original sign */
  2004.     return((char *)(r+1));
  2005. }
  2006.  
  2007. #ifndef NOB64
  2008. /* Base-64 conversion routines */
  2009.  
  2010. static char b64[] = {            /* Encoding vector */
  2011. #ifdef pdp11
  2012.   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
  2013. #else
  2014.   'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S',
  2015.   'T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l',
  2016.   'm','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4',
  2017.   '5','6','7','8','9','+','/','=','\0'
  2018. #endif /* pdp11 */
  2019. };
  2020. static int b64tbl[] = {            /* Decoding vector */
  2021.     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
  2022.     -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
  2023.     -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
  2024.     52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1,
  2025.     -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
  2026.     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
  2027.     -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  2028.     41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
  2029.     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  2030.     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  2031.     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  2032.     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  2033.     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  2034.     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  2035.     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  2036.     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
  2037. };
  2038.  
  2039. /*
  2040.    B 8 T O B 6 4  --  Converts 8-bit data to Base64 encoding.
  2041.  
  2042.    Call with:
  2043.      s   = Pointer to 8-bit data;
  2044.      n   = Number of source bytes to encode (SEE NOTE).
  2045.            If it's a null-terminated string, you can use -1 here.
  2046.      out = Address of output buffer.
  2047.      len = Length of output buffer (should > 4/3 longer than input).
  2048.  
  2049.    Returns:
  2050.      >= 0 if OK, number of bytes placed in output buffer,
  2051.           with the subsequent byte set to NUL if space permits.
  2052.      -1 on error (output buffer space exhausted).
  2053.  
  2054.    NOTE:
  2055.      If this function is to be called repeatedly, e.g. to encode a data
  2056.      stream a chunk at a time, the source length must be a multiple of 3
  2057.      in all calls but the final one to avoid the generation of extraneous
  2058.      pad characters that would throw the decoder out of sync.  When encoding
  2059.      only a single string, this is not a consideration.  No internal state
  2060.      is kept, so there is no reset function.
  2061. */
  2062. int
  2063. b8tob64(s,n,out,len) char * s,* out; int n, len; {
  2064.     int b3, b4, i, x = 0;
  2065.     unsigned int t;
  2066.  
  2067.     if (n < 0) n = strlen(s);
  2068.  
  2069.     for (i = 0; i < n; i += 3,x += 4) { /* Loop through source bytes */
  2070.     b3 = b4 = 0;
  2071.     t = (unsigned)((unsigned)((unsigned int)s[i] & 0xff) << 8);
  2072.     if (n - 1 > i) {        /* Do we have another after this? */
  2073.             t |= (unsigned)(s[i+1] & 0xff); /* Yes, OR it in */
  2074.             b3 = 1;            /* And remember */
  2075.         }
  2076.         t <<= 8;            /* Move over */
  2077.         if (n - 2 > i) {        /* Another one after that? */
  2078.             t |= (unsigned)(s[i+2] & 0xff); /* Yes, OR it in */
  2079.             b4 = 1;            /* and remember */
  2080.         }
  2081.     if (x + 4 > len)        /* Check output space */
  2082.       return(-1);
  2083.     out[x+3] = b64[b4 ? (t & 0x3f) : 64]; /* 64 = code for '=' */
  2084.         t >>= 6;
  2085.         out[x+2] = b64[b3 ? (t & 0x3f) : 64];
  2086.         t >>= 6;
  2087.         out[x+1] = b64[t & 0x3f];
  2088.         t >>= 6;
  2089.         out[x]   = b64[t & 0x3f];
  2090.     }
  2091.     if (x < len) out[x] = NUL;        /* Null-terminate the string */
  2092.     return(x);
  2093. }
  2094.  
  2095.  
  2096. /*
  2097.    B 6 4 T O B 8  --  Converts Base64 string to 8-bit data.
  2098.  
  2099.    Call with:
  2100.      s   = pointer to Base64 string (whitespace ignored).
  2101.      n   = length of string, or -1 if null terminated, or 0 to reset.
  2102.      out = address of output buffer.
  2103.      len = length of output buffer.
  2104.  
  2105.    Returns:
  2106.      >= 0 if OK, number of bytes placed in output buffer,
  2107.           with the subsequent byte set to NUL if space permits.
  2108.      <  0 on error:
  2109.        -1 = output buffer too small for input.
  2110.        -2 = input contains illegal characters.
  2111.        -3 = internal coding error.
  2112.  
  2113.    NOTE:
  2114.      Can be called repeatedly to decode a Base64 stream, one chunk at a
  2115.      time.  However, if it is to be called for multiple streams in
  2116.      succession, its internal state must be reset at the beginning of
  2117.      the new stream.
  2118. */
  2119. int
  2120. b64tob8(s,n,out,len) char * s,* out; int len; {    /* Decode */
  2121.     static int bits = 0;
  2122.     static unsigned int r = 0;
  2123.     int i, k = 0, x, t;
  2124.     unsigned char c;
  2125.  
  2126.     if (n == 0) {            /* Reset state */
  2127.     bits = 0;
  2128.     r = 0;
  2129.     return(0);
  2130.     }
  2131.     x = (n < 0) ? strlen(s) : n;    /* Source length */
  2132.  
  2133.     n = ((x + 3) / 4) * 3;        /* Compute destination length */
  2134.     if (x > 0 && s[x-1] == '=') n--;    /* Account for padding */
  2135.     if (x > 1 && s[x-2] == '=') n--;
  2136.     if (n > len)            /* Destination not big enough */
  2137.       return(-1);            /* Fail */
  2138.  
  2139.     for (i = 0; i < x; i++) {        /* Loop thru source */
  2140.     c = (CHAR)s[i];            /* Next char */
  2141.         t = b64tbl[c];            /* Code for this char */
  2142.     if (t == -2) {            /* Whitespace or Ctrl */
  2143.         n--;            /* Ignore */
  2144.         continue;
  2145.     } else if (t == -1) {        /* Illegal code */
  2146.         return(-2);            /* Fail. */
  2147.     } else if (t > 63 || t < 0)    /* Illegal value */
  2148.       return(-3);            /* fail. */
  2149.     bits += 6;            /* Count bits */
  2150.     r <<= 6;            /* Make space */
  2151.     r |= (unsigned) t;        /* OR in new code */
  2152.     if (bits >= 8) {        /* Have a byte yet? */
  2153.         bits -= 8;            /* Output it */
  2154.         c = (unsigned) ((r >> bits) & 0xff);
  2155.         out[k++] = c;
  2156.     }
  2157.     }
  2158.     if (k < len) out[k] = NUL;        /* Null-terminate in case it's */
  2159.     return(k);                /* a text string */
  2160. }
  2161. #endif /* NOB64 */
  2162.  
  2163. /* C H K N U M  --  See if argument string is an integer  */
  2164.  
  2165. /* Returns 1 if OK, zero if not OK */
  2166. /* If OK, string should be acceptable to atoi() */
  2167. /* Allows leading space, sign */
  2168.  
  2169. int
  2170. chknum(s) char *s; {            /* Check Numeric String */
  2171.     int x = 0;                /* Flag for past leading space */
  2172.     int y = 0;                /* Flag for digit seen */
  2173.     char c;
  2174.     debug(F110,"chknum",s,0);
  2175.     if (!s) return(0);
  2176.     if (!*s) return(0);
  2177.     while ((c = *s++)) {        /* For each character in the string */
  2178.     switch (c) {
  2179.       case SP:            /* Allow leading spaces */
  2180.       case HT:
  2181.         if (x == 0) continue;
  2182.         else return(0);
  2183.       case '+':            /* Allow leading sign */
  2184.       case '-':
  2185.         if (x == 0) x = 1;
  2186.         else return(0);
  2187.         break;
  2188.       default:            /* After that, only decimal digits */
  2189.         if (c >= '0' && c <= '9') {
  2190.         x = y = 1;
  2191.         continue;
  2192.         } else return(0);
  2193.     }
  2194.     }
  2195.     return(y);
  2196. }
  2197.  
  2198.  
  2199. /*  R D I G I T S  -- Verify that all characters in arg ARE DIGITS  */
  2200.  
  2201. /*  Returns 1 if so, 0 if not or if string is empty */
  2202.  
  2203. int
  2204. rdigits(s) char *s; {
  2205.     if (!s) return(0);
  2206.     do {
  2207.         if (!isdigit(*s)) return(0);
  2208.         s++;
  2209.     } while (*s);
  2210.     return(1);
  2211. }
  2212.  
  2213. /*  P A R N A M  --  Return parity name */
  2214.  
  2215. char *
  2216. #ifdef CK_ANSIC
  2217. parnam(char c)
  2218. #else
  2219. parnam(c) char c;
  2220. #endif /* CK_ANSIC */
  2221. /* parnam */ {
  2222.     switch (c) {
  2223.     case 'e': return("even");
  2224.     case 'o': return("odd");
  2225.     case 'm': return("mark");
  2226.     case 's': return("space");
  2227.     case 0:   return("none");
  2228.     default:  return("invalid");
  2229.     }
  2230. }
  2231.  
  2232. char *                    /* Convert seconds to hh:mm:ss */
  2233. #ifdef CK_ANSIC
  2234. hhmmss(long x)
  2235. #else
  2236. hhmmss(x) long x;
  2237. #endif /* CK_ANSIC */
  2238. /* hhmmss(x) */ {
  2239.     static char buf[10];
  2240.     long s, h, m;
  2241.     h = x / 3600L;            /* Hours */
  2242.     x = x % 3600L;
  2243.     m = x / 60L;            /* Minutes */
  2244.     s = x % 60L;            /* Seconds */
  2245.     if (x > -1L)
  2246.       sprintf(buf,"%02ld:%02ld:%02ld",h,m,s);
  2247.     else
  2248.       buf[0] = NUL;
  2249.     return((char *)buf);
  2250. }
  2251.  
  2252. /* L S E T  --  Set s into p, right padding to length n with char c; */
  2253. /*
  2254.    s is a NUL-terminated string.
  2255.    If length(s) > n, only n bytes are moved.
  2256.    The result is NOT NUL terminated unless c == NUL and length(s) < n.
  2257.    The intended of this routine is for filling in fixed-length record fields.
  2258. */
  2259. VOID
  2260. lset(p,s,n,c) char *s; char *p; int n; int c; {
  2261.     int x;
  2262. #ifndef USE_MEMCPY
  2263.     int i;
  2264. #endif /* USE_MEMCPY */
  2265.     if (!s) s = "";
  2266.     x = strlen(s);
  2267.     if (x > n) x = n;
  2268. #ifdef USE_MEMCPY
  2269.     memcpy(p,s,x);
  2270.     if (n > x)
  2271.       memset(p+x,c,n-x);
  2272. #else
  2273.     for (i = 0; i < x; i++)
  2274.       *p++ = *s++;
  2275.     for (; i < n; i++)
  2276.       *p++ = c;
  2277. #endif /* USE_MEMCPY */
  2278. }
  2279.  
  2280. /* R S E T  --  Right-adjust s in p, left padding to length n with char c */
  2281.  
  2282. VOID
  2283. rset(p,s,n,c) char *s; char *p; int n; int c; {
  2284.     int x;
  2285. #ifndef USE_MEMCPY
  2286.     int i;
  2287. #endif /* USE_MEMCPY */
  2288.     if (!s) s = "";
  2289.     x = strlen(s);
  2290.     if (x > n) x = n;
  2291. #ifdef USE_MEMCPY
  2292.     memset(p,c,n-x);
  2293.     memcpy(p+n-x,s,x);
  2294. #else
  2295.     for (i = 0; i < (n - x); i++)
  2296.       *p++ = c;
  2297.     for (; i < n; i++)
  2298.       *p++ = *s++;
  2299. #endif /* USE_MEMCPY */
  2300. }
  2301.  
  2302. /*  U L O N G T O H E X  --  Unsigned long to hex  */
  2303.  
  2304. /*
  2305.   Converts unsigned long arg to hex and returns string pointer to
  2306.   rightmost n hex digits left padded with 0's.  Allows for longs
  2307.   up to 64 bits.  Returns pointer to result.
  2308. */
  2309. char *
  2310. #ifdef CK_ANSIC
  2311. ulongtohex( unsigned long z, int n )
  2312. #else
  2313. ulongtohex(z,n) unsigned long z; int n; 
  2314. #endif    /* CK_ANSIC */
  2315. /* ulongtohex */ {
  2316.     static char hexbuf[17];
  2317.     int i = 16, x, k = 0;
  2318.     hexbuf[16] = '\0';
  2319.     if (n > 16) n = 16;
  2320.     k = 2 * (sizeof(long));
  2321.     for (i = 0; i < n; i++) {
  2322.     if (i > k || z == 0) {
  2323.         hexbuf[15-i] = '0';
  2324.     } else {
  2325.         x = z & 0x0f;
  2326.         z = z >> 4;
  2327.         hexbuf[15-i] = x + ((x < 10) ? '0' : 0x37);
  2328.     }
  2329.     }
  2330.     return((char *)(&hexbuf[16-i]));
  2331. }
  2332.  
  2333. /*  H E X T O U L O N G  --  Hex string to unsigned long  */
  2334.  
  2335. /*
  2336.   Converts n chars from s from hex to unsigned long.
  2337.   Returns:
  2338.    0L or positive, good result (0L is returned if arg is NULL or empty).
  2339.   -1L on error: non-hex arg or overflow.
  2340. */
  2341. long
  2342. hextoulong(s,n) char *s; int n; {
  2343.     char buf[64];
  2344.     unsigned long result = 0L;
  2345.     int d, count = 0;
  2346.     int flag = 0;
  2347.     if (!s) s = "";
  2348.     if (!*s) {
  2349.     return(0L);
  2350.     }
  2351.     if (n < 1)
  2352.       return(0L);
  2353.     if (n > 63) n = 63;
  2354.     strncpy(buf,s,n);
  2355.     buf[n] = '\0';
  2356.     s = buf;
  2357.     while (*s) {
  2358.     d = *s++;
  2359.     if ((d == '0' || d == ' ')) {
  2360.         if (!flag)
  2361.           continue;
  2362.     } else {
  2363.         flag = 1;
  2364.     }
  2365.     if (islower(d))
  2366.       d = toupper(d);
  2367.     if (d >= '0' && d <= '9') {
  2368.         d -= 0x30;
  2369.     } else if (d >= 'A' && d <= 'F') {
  2370.         d -= 0x37;
  2371.     } else {
  2372.         return(-1L);
  2373.     }
  2374.     if (++count > (sizeof(long) * 2))
  2375.       return(-1L);
  2376.     result = (result << 4) | (d & 0x0f);
  2377.     }
  2378.     return(result);
  2379. }
  2380.  
  2381. /*
  2382.   c k s p l i t  --  Splits a string into words, or:
  2383.                      extracts a given word from a string.
  2384.  
  2385.   Allows for grouping.
  2386.   Operates on a copy of the string; does not alter the original string.
  2387.   All strings NUL-terminated.
  2388.  
  2389.   Call with:
  2390.     fc = function code:
  2391.          1 = split, 0 = word.
  2392.     n1 = desired word number if fc == 0.
  2393.     s1 = source string.
  2394.     s2 = break string (NULL to accept default = all non-alphanum).
  2395.     s3 = include string (NULL to accept default = all alphanum).
  2396.     n2 = grouping mask (OR desired ones together):
  2397.          1 = doublequotes,  2 = braces,    4 = apostrophes,
  2398.          8 = parens,       16 = brackets, 32 = angle brackets,
  2399.         -1 = 63 = all of these.
  2400.     n3 = group quote character, ASCII value, used and tested only for
  2401.          LISP quote, e.g. (a 'b c '(d e f)).
  2402.     n4 = 0 to collapse adjacent separators;
  2403.          nonzero not to collapse them.
  2404.  
  2405.   Returns:
  2406.     Pointer to struct stringarray, with size:
  2407.       -1 = memory allocation error.
  2408.       -2 = too many words in string.
  2409.        n = number of words (0 or more).
  2410.  
  2411.   With:
  2412.     wordarray = array of pointers to n words (n == 1 if fc == 0), 1-based.
  2413.     Each pointer is to a malloc'd string.  This array is recycled upon each
  2414.     call; if you need to keep the strings, make copies of them.  This routine
  2415.     must have control of allocation and deallocation.
  2416.  
  2417.   If a given character is included in the include list, it is not treated
  2418.   as a separator or as a grouping character.
  2419.  
  2420.   Groups may be nested only if they are formed with braces, parens, or
  2421.   brackets, but not with quotes or apostrophes since ASCII quotes have no
  2422.   intrinsic handedness.  Group-start and end characters are treated as
  2423.   separators even in the absence of other separators, so a string such as
  2424.   "a{b}c" results in three words, not one.
  2425.  
  2426.   Sample call to split a string into an array:
  2427.     struct stringarray * q;
  2428.     q = cksplit(1,0,s1,s2,s3,-1,0);
  2429.         q->a_size = size (>=0) or failure code (<0)
  2430.         q->a_head = pointer to array (elements 0 thru q->asize - 1).
  2431.  
  2432.   Sample call to extract word n from a string:
  2433.     struct stringarray * q;
  2434.     q = cksplit(0,n,s1,s2,s3,-1,0);
  2435.         q->a_size = size (1) or failure code (<0)
  2436.         q->a_head = pointer to array (element 1 is the desired word).
  2437. */
  2438.  
  2439. /* States */
  2440.  
  2441. #define ST_BW  0            /* Between Words */
  2442. #define ST_IW  1            /* In Word */
  2443. #define ST_IG  2            /* Start Group */
  2444.  
  2445. /* Character Classes (bitmap) */
  2446.  
  2447. #define CL_SEP 1            /* Separator */
  2448. #define CL_OPN 2            /* Group Open */
  2449. #define CL_CLS 4            /* Group Close */
  2450. #define CL_DAT 8            /* Data */
  2451. #define CL_QUO 16            /* Group quote */
  2452.  
  2453. #ifdef BIGBUFOK
  2454. #ifndef MAXWORDS
  2455. #define MAXWORDS 4096            /* Max number of words */
  2456. #endif /* MAXWORDS */
  2457. #ifndef NESTMAX
  2458. #define NESTMAX 64            /* Maximum nesting level */
  2459. #endif /* NESTMAX */
  2460. #else
  2461. #ifndef MAXWORDS
  2462. #define MAXWORDS 128            /* Max number of words */
  2463. #endif /* MAXWORDS */
  2464. #ifndef NESTMAX
  2465. #define NESTMAX 16            /* Maximum nesting level */
  2466. #endif /* NESTMAX */
  2467. #endif /* BIGBUFOK */
  2468.  
  2469. /* static */ char ** wordarray = NULL;    /* Result array of word pointers */
  2470.  
  2471. static struct stringarray ck_sval =  {    /* Return value structure */
  2472.     NULL,                /* Pointer to array */
  2473.     0                    /* Size */
  2474. };
  2475. static int * wordsize = NULL;
  2476.  
  2477. static VOID
  2478. setword(n,s,len) int n, len; char * s; {
  2479.     register char * p;
  2480.     register int i, k;
  2481.  
  2482.     if (!s) s = "";
  2483.  
  2484.     if (!wordarray) {            /* Allocate result array (only once) */
  2485.     if (!(wordarray = (char **)malloc((MAXWORDS+1) * sizeof(char *))))
  2486.       return;
  2487.     if (!(wordsize = (int *)malloc((MAXWORDS+1) * sizeof(int))))
  2488.       return;
  2489.     for (i = 0; i <= MAXWORDS; i++)    { /* Initialize result array */
  2490.         wordarray[i] = NULL;
  2491.         wordsize[i] = 0;
  2492.     }
  2493.     }
  2494.     if (wordsize[n] < len /* || !wordarray[n] */ ) {
  2495.     k = (len < 16) ? 16 : len + (len / 4);
  2496.     wordarray[n] = (char *) malloc(k+1);
  2497.     wordsize[n] = (wordarray[n]) ? k : 0;
  2498.     if (wordarray[n]) {
  2499.         p = wordarray[n];
  2500.         while ((*p++ = *s++) && k-- > 0) ;
  2501.     }
  2502.     } else if (len > 0) {
  2503.     k = wordsize[n];        /* (In case len arg is a lie) */
  2504.     p = wordarray[n];
  2505.     while ((*p++ = *s++) && k-- > 0) {
  2506. #ifdef COMMENT
  2507.         if ((*(s-1) == CMDQ) && *s != CMDQ) {
  2508.         k++;
  2509.         p--;
  2510.         }
  2511. #endif /* COMMENT */
  2512.     }
  2513.     } else if (wordarray[n]) {
  2514.     wordarray[n][0] = NUL;
  2515.     }
  2516. }
  2517.  
  2518. static char * splitbuf = NULL;
  2519. static int nsplitbuf = 0;
  2520.  
  2521. /* n4 = 1 to NOT collapse adjacent separators */
  2522.  
  2523.  
  2524. struct stringarray *
  2525. cksplit(fc,n1,s1,s2,s3,n2,n3,n4) int fc,n1,n2,n3,n4; char *s1, *s2, *s3; {
  2526.     int splitting = 0;            /* What I was asked to do */
  2527.     int i, k, ko = 0, n, x, max = MAXWORDS; /* Workers */
  2528.     char * s = NULL, * ss, * p;        /* Workers */
  2529.     char * sep = "";            /* Default break set */
  2530.     char * notsep = "";            /* Default include set */
  2531.     int    grouping = 0;        /* Grouping option */
  2532.     char * gr_opn = "\"{'([<";        /* Group open brackets */
  2533.     char * gr_cls = "\"}')]>";        /* Group close brackets */
  2534.     int    gr_stk[NESTMAX];        /* Nesting bracket stack */
  2535.     int    gr_lvl = 0;            /* Nesting level */
  2536.     int    wordnum = 0;            /* Current word number */
  2537.     char   c = 'A';            /* Current char (dummy start value) */
  2538.     int    class = 0;            /* Current character class */
  2539.     int    state = ST_BW;        /* Current FSA state */
  2540.     int    len = 0;            /* Length of current word */
  2541.     int    slen = 0;            /* Length of s1 */
  2542.     int    gquote = 0;            /* Quoted group */
  2543.     int    cquote = 0;            /* Quoted character */
  2544.     int    collapse = 1;        /* Collapse adjacent separators */
  2545.  
  2546.     if (n4) collapse = 0;        /* Don't collapse */
  2547.  
  2548.     for (i = 0; i < NESTMAX; i++)    /* Initialize nesting stack */
  2549.       gr_stk[i] = 0;
  2550.  
  2551.     setword(1,NULL,0);
  2552.     ck_sval.a_head = wordarray;        /* Initialize return value struct */
  2553.     ck_sval.a_size = 0;
  2554.  
  2555.     if (!s1) s1 = "";            /* s1 = source string */
  2556.     if (!*s1) {                /* If none, nothing to do */
  2557.     return(&ck_sval);
  2558.     }
  2559.     splitting = fc;            /* Our job */
  2560.     if (splitting) {            /* If splitting n = word count */
  2561.     n = 0;                /* Initialize it */
  2562.     } else {                /* Otherwise */
  2563.     if (n1 < 1) {            /* If 0 (or less) */
  2564.         ck_sval.a_size = 0;        /* nothing to do. */
  2565.         return(&ck_sval);
  2566.     }
  2567.     n = n1;                /* n = desired word number. */
  2568.     }
  2569.     slen = 0;                /* Get length of s1 */
  2570.     debug(F111,"cksplit",s1,n);
  2571.  
  2572.     p = s1;
  2573. #ifdef COMMENT
  2574.     while (*p++) slen++;        /* Make pokeable copy of s1 */
  2575.     if (!splitbuf || slen > nsplitbuf) { /* Allocate buffer if needed */
  2576.     int xx;
  2577.     if (splitbuf)
  2578.       free(splitbuf);
  2579.     xx = (slen < 255) ? 255 : xx + (xx / 4);
  2580.     debug(F101,"cksplit splitbuf","",xx);
  2581.     splitbuf = (char *)malloc(xx+1);
  2582.     if (!splitbuf) {        /* Memory allocation failure... */
  2583.         ck_sval.a_size = -1;
  2584.         return(&ck_sval);
  2585.     }
  2586.     nsplitbuf = xx;            /* Remember size of buffer */
  2587.     }
  2588. #else
  2589. /*
  2590.   The idea is to just copy the string into splitbuf (if it exists).  This
  2591.   gives us both the copy and the length so we only need to grovel through the
  2592.   string once in most cases.  Only when splitbuf doesn't exist or is too short
  2593.   do we re-malloc(), which should be very infrequent so who cares if we have
  2594.   to go through the string again in that case.
  2595. */
  2596.     p = s1;
  2597.     s = splitbuf;
  2598.     if (splitbuf) {            /* Make pokeable copy of s1 */
  2599.     while ((*s++ = *p++) && (slen++ < nsplitbuf)) /* Try to copy */
  2600.       ;
  2601.     }
  2602.     if (!splitbuf || slen >= nsplitbuf) { /* Need to do more... */
  2603.     int xx;
  2604.     if (splitbuf)            /* Free previous buf if any */
  2605.       free(splitbuf);
  2606.     while (*p++) slen++;        /* Get (rest of) length */
  2607.     xx = (slen < 255) ? 255 : slen + (slen / 4); /* Size of new buffer */
  2608.     splitbuf = (char *)malloc(xx+1); /* Allocate it */
  2609.     if (!splitbuf) {         /* Memory allocation failure... */
  2610.         ck_sval.a_size = -1;
  2611.         return(&ck_sval);
  2612.     }
  2613.     nsplitbuf = xx;            /* Remember (new) buffer size */
  2614.     s = splitbuf;
  2615.     p = s1;
  2616.     while ((*s++ = *p++)) ;
  2617.     }
  2618.  
  2619. #endif /* COMMENT */
  2620.     s = splitbuf;
  2621.     sep = s2;                /* s2 = break set */
  2622.     if (!sep) sep = "";
  2623.     notsep = s3;            /* s3 = include set */
  2624.     if (!notsep) notsep = "";
  2625.     if (n2 < 0) n2 = 63;        /* n2 = grouping mask */
  2626.     grouping = n2;
  2627.     p = "";                /* Pointer to current word */
  2628.     while (c) {                /* Loop through string */
  2629.     c = *s;
  2630.     class = 0;
  2631.     if (!cquote && c == CMDQ) {    /* If CMDQ */
  2632.         cquote++;            /* next one is quoted */
  2633.         goto nextc;            /* go get it */
  2634.     }
  2635.     if (cquote && c == CMDQ) {    /* Quoted CMDQ is special */
  2636.         if (state != ST_BW) {    /* because it can still separate */
  2637.         char * s2 = s-1;
  2638.         while (s2 > p) { *s2 = *(s2-1); s2--; }
  2639.         p++;
  2640.         }
  2641.         cquote = 0;
  2642.     }
  2643.     if (cquote) {            /* Other quoted character */
  2644.         if (state != ST_BW) {    /* can't separate or group */
  2645.         char * s2 = s-1;
  2646.         while (s2 > p) { *s2 = *(s2-1); s2--; }
  2647.         p++;
  2648.         }
  2649.         class = CL_DAT;        /* so treat it as data */
  2650.         cquote = 0;
  2651.         x = 1;
  2652.     } else {            /* Character is not quoted */
  2653.         if (c < SP) {        /* Get its class */
  2654.         x = 0;            /* x == 0 means "is separator" */
  2655.         } else if (*sep) {        /* Break set given */
  2656.         ss = sep;
  2657.         while (*ss && *ss != c) ss++; /* (instead of ckstrchr()) */
  2658.         x = (*ss != c);
  2659.         } else {            /* Default break set is */
  2660.         x = ((c >= 'a' && c <= 'z') || /* all but alphanumerics */
  2661.              (c >= '0' && c <= '9') ||
  2662.              (c >= 'A' && c <= 'Z')
  2663.              );
  2664.         }
  2665.         if (x == 0 && *notsep && c) { /* Include set if given */
  2666.         ss = notsep;
  2667.         while (*ss && *ss != c) ss++; /* (instead of ckstrchr()) */
  2668.         x = (*ss == c);
  2669.         }
  2670.         if (c == n3 && grouping && state == ST_BW) { /* Group quote? */
  2671.         class = CL_QUO;
  2672.         } else {
  2673.         class = x ? CL_DAT : CL_SEP; /* Class = data or separator */
  2674.         }
  2675.         if (grouping) {        /* Grouping? */
  2676.         int j;            /* Look for group start */
  2677.         for (k = 0; k < 6; k++) { /* Group-start char? */
  2678.             j = 1 << k;        /* Get its mask bit value */
  2679.             if (grouping & j) {
  2680.             if (c == gr_opn[k]) { /* Selected group opener? */
  2681.                 ko = k;
  2682.                 class |= CL_OPN;
  2683.                 if (c == '"' || c == '\'') { /* These can also */
  2684.                 class |= CL_CLS;         /* be closers */
  2685.                 break;
  2686.                 }
  2687.             } else if (c == gr_cls[k]) { /* Group closer? */
  2688.                 class |= CL_CLS;
  2689.                 break;
  2690.             }
  2691.             }
  2692.         }
  2693.         }
  2694.     }
  2695.     switch (state) {        /* State switcher... */
  2696.       case ST_BW:            /* BETWEENWORDS */
  2697.         if (class & CL_OPN) {    /* Group opener */
  2698.         if (gr_lvl == 0 && !gquote) { /* If not in group */
  2699.             p = s;        /* point to beginning of word */
  2700.         }
  2701.         gr_lvl++;        /* Push closer on nesting stack */
  2702.         if (gr_lvl >= NESTMAX)
  2703.           goto xxsplit;
  2704.         gr_stk[gr_lvl] = gr_cls[ko];
  2705.         state = ST_IG;        /* Switch to INGROUP state */
  2706.         } else if (class & CL_DAT) { /* Data character */
  2707.         gr_lvl = 0;        /* Clear group nesting stack */
  2708.         gr_stk[gr_lvl] = 0;
  2709.         len = 0;
  2710.         p = s;            /* Point to beginning of word */
  2711.         if (gquote) {        /* Adjust for quote */
  2712.             len++;
  2713.             p--;
  2714.             gquote = 0;
  2715.         }
  2716.         state = ST_IW;        /* Switch to INWORD state */
  2717.         } else if (class & CL_QUO) { /* Group quote */
  2718.         gquote = gr_lvl+1;    /* Remember quoted level */
  2719.         p = s - 1;
  2720.         len = 1;
  2721.         }
  2722.         if (collapse)
  2723.           break;
  2724.  
  2725.       case ST_IW:            /* INWORD (but not in a group) */
  2726.         if (class & CL_SEP) {    /* Ends on any kind of separator */
  2727.         *s = NUL;        /* Terminate this word */
  2728.         wordnum++;        /* Count it */
  2729.         if (splitting) {    /* Dispose of it appropriately */
  2730.             if (wordnum > max) {   /* Add to array if splitting */
  2731.             ck_sval.a_size = -2;
  2732.             return(&ck_sval);
  2733.             }
  2734.             setword(wordnum,p,len);
  2735.         } else if (wordnum == n) { /* Searching for word n */
  2736.             setword(1,p,len);
  2737.             ck_sval.a_size = 1;
  2738.             return(&ck_sval);
  2739.         }
  2740.         state = ST_BW;        /* Switch to BETWEENWORDS state */
  2741.         len = 0;
  2742.         }
  2743.         break;
  2744.  
  2745.       case ST_IG:            /* INGROUP */
  2746.         if (class & CL_CLS) {    /* Have group closer? */
  2747.         if (c == gr_stk[gr_lvl]) { /* Does it match current opener? */
  2748.             gr_lvl--;           /* Yes, pop stack */
  2749.             if (gr_lvl < 0)       /* Don't pop it too much */
  2750.               gr_lvl = 0;
  2751.             if (gr_lvl == 0) {    /* If at top of stack */
  2752.             if (gquote)
  2753.               s++;
  2754.             c = *s;
  2755.             *s = NUL;    /* we have word. */
  2756.  
  2757.             wordnum++;    /* Count and dispose of it. */
  2758.             len--;
  2759.             if (splitting) {
  2760.                 if (wordnum > max) {
  2761.                 ck_sval.a_size = -2;
  2762.                 return(&ck_sval);
  2763.                 }
  2764.                 setword(wordnum,p+1,len);
  2765.             } else if (wordnum == n) {
  2766.                 setword(1,p+1,len);
  2767.                 ck_sval.a_size = 1;
  2768.                 return(&ck_sval);
  2769.             }
  2770.             state = ST_BW;    /* Switch to BETWEENWORDS state */
  2771.             len = 0;
  2772.             }
  2773.             if (gr_lvl < gquote)
  2774.               gquote = 0;
  2775.         }
  2776.         } else if (class & CL_OPN) { /* Have group opener */
  2777.         gr_lvl++;         /* Push on nesting stack */
  2778.         if (gr_lvl >= NESTMAX) goto xxsplit;
  2779.         gr_stk[gr_lvl] = gr_cls[ko];
  2780.         }
  2781.     } /* switch */
  2782.  
  2783.       nextc:
  2784.     s++;                /* Next char */
  2785.     if (state)
  2786.       len++;
  2787.     } /* while (c) */
  2788.  
  2789.     if (gr_lvl > 0) {            /* In case of an unclosed group */
  2790.     if (splitting) {        /* make it the last word. */
  2791.         if (++wordnum > max) {
  2792.         ck_sval.a_size = -2;
  2793.         return(&ck_sval);
  2794.         }
  2795.         setword(wordnum,p+1,len);
  2796.     } else if (wordnum == n) {
  2797.         setword(1,p+1,len);
  2798.         ck_sval.a_size = 1;
  2799.         return(&ck_sval);
  2800.     }
  2801.     }
  2802.     if (!splitting) {            /* Wanted word n but there was none? */
  2803.     setword(1,NULL,0);
  2804.     ck_sval.a_size = 0;
  2805.     return(&ck_sval);
  2806.     } else {                /* Succeed otherwise */
  2807.     ck_sval.a_size = wordnum;
  2808.     if (wordnum < MAXWORDS)
  2809.       setword(wordnum+1,NULL,0);
  2810.     }
  2811. #ifdef DEBUG
  2812.     if (deblog) {
  2813.     for (i = 1; i <= wordnum; i++)
  2814.       debug(F111,"cksplit result",wordarray[i],i);
  2815.     }
  2816. #endif /* DEBUG */
  2817.     return(&ck_sval);
  2818.  
  2819.   xxsplit:                /* Error return */
  2820.     ck_sval.a_size = -2;
  2821.     return(&ck_sval);
  2822. }
  2823.  
  2824. /* End of ckclib.c */
  2825.