home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / textutils-1.11-src.lha / textutils-1.11 / src / sort.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-13  |  42.8 KB  |  1,852 lines

  1. /* sort - sort lines of text (with all kinds of options).
  2.    Copyright (C) 1988, 1991, 1992, 1993, 1994 Free Software Foundation
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written December 1988 by Mike Haertel.
  19.    The author may be reached (Email) at the address mike@gnu.ai.mit.edu,
  20.    or (US mail) as Mike Haertel c/o Free Software Foundation. */
  21.  
  22. #include <config.h>
  23.  
  24. /* Get isblank from GNU libc.  */
  25. #define _GNU_SOURCE
  26.  
  27. #include <sys/types.h>
  28. #include <signal.h>
  29. #include <stdio.h>
  30. #include "system.h"
  31. #include "version.h"
  32. #include "long-options.h"
  33. #include "safe-stat.h"
  34.  
  35. #ifdef _POSIX_VERSION
  36. #include <limits.h>
  37. #else
  38. #ifndef UCHAR_MAX
  39. #define UCHAR_MAX 255
  40. #endif
  41. #endif
  42. #ifndef STDC_HEADERS
  43. char *malloc ();
  44. char *realloc ();
  45. void free ();
  46. #endif
  47.  
  48. void error ();
  49. static void usage ();
  50.  
  51. #define min(a, b) ((a) < (b) ? (a) : (b))
  52. #define UCHAR_LIM (UCHAR_MAX + 1)
  53. #define UCHAR(c) ((unsigned char) (c))
  54.  
  55. /* The kind of blanks for '-b' to skip in various options. */
  56. enum blanktype { bl_start, bl_end, bl_both };
  57.  
  58. /* The name this program was run with. */
  59. char *program_name;
  60.  
  61. /* Table of digits. */
  62. static int digits[UCHAR_LIM];
  63.  
  64. /* Table of white space. */
  65. static int blanks[UCHAR_LIM];
  66.  
  67. /* Table of non-printing characters. */
  68. static int nonprinting[UCHAR_LIM];
  69.  
  70. /* Table of non-dictionary characters (not letters, digits, or blanks). */
  71. static int nondictionary[UCHAR_LIM];
  72.  
  73. /* Translation table folding lower case to upper. */
  74. static char fold_toupper[UCHAR_LIM];
  75.  
  76. /* Table mapping 3-letter month names to integers.
  77.    Alphabetic order allows binary search. */
  78. static struct month
  79. {
  80.   char *name;
  81.   int val;
  82. } const monthtab[] =
  83. {
  84.   {"APR", 4},
  85.   {"AUG", 8},
  86.   {"DEC", 12},
  87.   {"FEB", 2},
  88.   {"JAN", 1},
  89.   {"JUL", 7},
  90.   {"JUN", 6},
  91.   {"MAR", 3},
  92.   {"MAY", 5},
  93.   {"NOV", 11},
  94.   {"OCT", 10},
  95.   {"SEP", 9}
  96. };
  97.  
  98. /* During the merge phase, the number of files to merge at once. */
  99. #define NMERGE 16
  100.  
  101. /* Initial buffer size for in core sorting.  Will not grow unless a
  102.    line longer than this is seen. */
  103. static int sortalloc =  524288;
  104.  
  105. /* Initial buffer size for in core merge buffers.  Bear in mind that
  106.    up to NMERGE * mergealloc bytes may be allocated for merge buffers. */
  107. static int mergealloc =  16384;
  108.  
  109. /* Guess of average line length. */
  110. static int linelength = 30;
  111.  
  112. /* Maximum number of elements for the array(s) of struct line's, in bytes.  */
  113. #define LINEALLOC 262144
  114.  
  115. /* Prefix for temporary file names. */
  116. static char *temp_file_prefix;
  117.  
  118. /* Flag to reverse the order of all comparisons. */
  119. static int reverse;
  120.  
  121. /* Flag for stable sort.  This turns off the last ditch bytewise
  122.    comparison of lines, and instead leaves lines in the same order
  123.    they were read if all keys compare equal.  */
  124. static int stable;
  125.  
  126. /* Tab character separating fields.  If NUL, then fields are separated
  127.    by the empty string between a non-whitespace character and a whitespace
  128.    character. */
  129. static char tab;
  130.  
  131. /* Flag to remove consecutive duplicate lines from the output.
  132.    Only the last of a sequence of equal lines will be output. */
  133. static int unique;
  134.  
  135. /* Nonzero if any of the input files are the standard input. */
  136. static int have_read_stdin;
  137.  
  138. /* Lines are held in core as counted strings. */
  139. struct line
  140. {
  141.   char *text;            /* Text of the line. */
  142.   int length;            /* Length not including final newline. */
  143.   char *keybeg;            /* Start of first key. */
  144.   char *keylim;            /* Limit of first key. */
  145. };
  146.  
  147. /* Arrays of lines. */
  148. struct lines
  149. {
  150.   struct line *lines;        /* Dynamically allocated array of lines. */
  151.   int used;            /* Number of slots used. */
  152.   int alloc;            /* Number of slots allocated. */
  153.   int limit;            /* Max number of slots to allocate.  */
  154. };
  155.  
  156. /* Input buffers. */
  157. struct buffer
  158. {
  159.   char *buf;            /* Dynamically allocated buffer. */
  160.   int used;            /* Number of bytes used. */
  161.   int alloc;            /* Number of bytes allocated. */
  162.   int left;            /* Number of bytes left after line parsing. */
  163. };
  164.  
  165. /* Lists of key field comparisons to be tried. */
  166. static struct keyfield
  167. {
  168.   int sword;            /* Zero-origin 'word' to start at. */
  169.   int schar;            /* Additional characters to skip. */
  170.   int skipsblanks;        /* Skip leading white space at start. */
  171.   int eword;            /* Zero-origin first word after field. */
  172.   int echar;            /* Additional characters in field. */
  173.   int skipeblanks;        /* Skip trailing white space at finish. */
  174.   int *ignore;            /* Boolean array of characters to ignore. */
  175.   char *translate;        /* Translation applied to characters. */
  176.   int numeric;            /* Flag for numeric comparison. */
  177.   int month;            /* Flag for comparison by month name. */
  178.   int reverse;            /* Reverse the sense of comparison. */
  179.   struct keyfield *next;    /* Next keyfield to try. */
  180. } keyhead;
  181.  
  182. /* The list of temporary files. */
  183. static struct tempnode
  184. {
  185.   char *name;
  186.   struct tempnode *next;
  187. } temphead;
  188.  
  189. /* Clean up any remaining temporary files. */
  190.  
  191. static void
  192. cleanup ()
  193. {
  194.   struct tempnode *node;
  195.  
  196.   for (node = temphead.next; node; node = node->next)
  197.     unlink (node->name);
  198. }
  199.  
  200. /* Allocate N bytes of memory dynamically, with error checking.  */
  201.  
  202. char *
  203. xmalloc (n)
  204.      unsigned n;
  205. {
  206.   char *p;
  207.  
  208.   p = malloc (n);
  209.   if (p == 0)
  210.     {
  211.       error (0, 0, "virtual memory exhausted");
  212.       cleanup ();
  213.       exit (2);
  214.     }
  215.   return p;
  216. }
  217.  
  218. /* Change the size of an allocated block of memory P to N bytes,
  219.    with error checking.
  220.    If P is NULL, run xmalloc.
  221.    If N is 0, run free and return NULL.  */
  222.  
  223. char *
  224. xrealloc (p, n)
  225.      char *p;
  226.      unsigned n;
  227. {
  228.   if (p == 0)
  229.     return xmalloc (n);
  230.   if (n == 0)
  231.     {
  232.       free (p);
  233.       return 0;
  234.     }
  235.   p = realloc (p, n);
  236.   if (p == 0)
  237.     {
  238.       error (0, 0, "virtual memory exhausted");
  239.       cleanup ();
  240.       exit (2);
  241.     }
  242.   return p;
  243. }
  244.  
  245. static FILE *
  246. xfopen (file, how)
  247.      char *file, *how;
  248. {
  249.   FILE *fp = strcmp (file, "-") ? fopen (file, how) : stdin;
  250.  
  251.   if (fp == 0)
  252.     {
  253.       error (0, errno, "%s", file);
  254.       cleanup ();
  255.       exit (2);
  256.     }
  257.   if (fp == stdin)
  258.     have_read_stdin = 1;
  259.   return fp;
  260. }
  261.  
  262. static void
  263. xfclose (fp)
  264.      FILE *fp;
  265. {
  266.   fflush (fp);
  267.   if (fp != stdin && fp != stdout)
  268.     {
  269.       if (fclose (fp) != 0)
  270.     {
  271.       error (0, errno, "error closing file");
  272.       cleanup ();
  273.       exit (2);
  274.     }
  275.     }
  276.   else
  277.     /* Allow reading stdin from tty more than once. */
  278.     clearerr (fp);
  279. }
  280.  
  281. static void
  282. xfwrite (buf, size, nelem, fp)
  283.      char *buf;
  284.      int size, nelem;
  285.      FILE *fp;
  286. {
  287.   if (fwrite (buf, size, nelem, fp) != nelem)
  288.     {
  289.       error (0, errno, "write error");
  290.       cleanup ();
  291.       exit (2);
  292.     }
  293. }
  294.  
  295. /* Return a name for a temporary file. */
  296.  
  297. static char *
  298. tempname ()
  299. {
  300.   static int seq;
  301.   int len = strlen (temp_file_prefix);
  302.   char *name = xmalloc (len + 16);
  303.   struct tempnode *node =
  304.   (struct tempnode *) xmalloc (sizeof (struct tempnode));
  305.  
  306.   if (len && temp_file_prefix[len - 1] != '/')
  307.     sprintf (name, "%s/sort%5.5d%5.5d", temp_file_prefix, getpid (), ++seq);
  308.   else
  309.     sprintf (name, "%ssort%5.5d%5.5d", temp_file_prefix, getpid (), ++seq);
  310.   node->name = name;
  311.   node->next = temphead.next;
  312.   temphead.next = node;
  313.   return name;
  314. }
  315.  
  316. /* Search through the list of temporary files for NAME;
  317.    remove it if it is found on the list. */
  318.  
  319. static void
  320. zaptemp (name)
  321.      char *name;
  322. {
  323.   struct tempnode *node, *temp;
  324.  
  325.   for (node = &temphead; node->next; node = node->next)
  326.     if (!strcmp (name, node->next->name))
  327.       break;
  328.   if (node->next)
  329.     {
  330.       temp = node->next;
  331.       unlink (temp->name);
  332.       free (temp->name);
  333.       node->next = temp->next;
  334.       free ((char *) temp);
  335.     }
  336. }
  337.  
  338. /* Initialize the character class tables. */
  339.  
  340. static void
  341. inittables ()
  342. {
  343.   int i;
  344.  
  345.   for (i = 0; i < UCHAR_LIM; ++i)
  346.     {
  347.       if (ISBLANK (i))
  348.     blanks[i] = 1;
  349.       if (ISDIGIT (i))
  350.     digits[i] = 1;
  351.       if (!ISPRINT (i))
  352.     nonprinting[i] = 1;
  353.       if (!ISALNUM (i) && !ISBLANK (i))
  354.     nondictionary[i] = 1;
  355.       if (ISLOWER (i))
  356.     fold_toupper[i] = toupper (i);
  357.       else
  358.     fold_toupper[i] = i;
  359.     }
  360. }
  361.  
  362. /* Initialize BUF, allocating ALLOC bytes initially. */
  363.  
  364. static void
  365. initbuf (buf, alloc)
  366.      struct buffer *buf;
  367.      int alloc;
  368. {
  369.   buf->alloc = alloc;
  370.   buf->buf = xmalloc (buf->alloc);
  371.   buf->used = buf->left = 0;
  372. }
  373.  
  374. /* Fill BUF reading from FP, moving buf->left bytes from the end
  375.    of buf->buf to the beginning first.    If EOF is reached and the
  376.    file wasn't terminated by a newline, supply one.  Return a count
  377.    of bytes buffered. */
  378.  
  379. static int
  380. fillbuf (buf, fp)
  381.      struct buffer *buf;
  382.      FILE *fp;
  383. {
  384.   int cc;
  385.  
  386.   bcopy (buf->buf + buf->used - buf->left, buf->buf, buf->left);
  387.   buf->used = buf->left;
  388.  
  389.   while (!feof (fp) && (buf->used == 0 || !memchr (buf->buf, '\n', buf->used)))
  390.     {
  391.       if (buf->used == buf->alloc)
  392.     {
  393.       buf->alloc *= 2;
  394.       buf->buf = xrealloc (buf->buf, buf->alloc);
  395.     }
  396.       cc = fread (buf->buf + buf->used, 1, buf->alloc - buf->used, fp);
  397.       if (ferror (fp))
  398.     {
  399.       error (0, errno, "read error");
  400.       cleanup ();
  401.       exit (2);
  402.     }
  403.       buf->used += cc;
  404.     }
  405.  
  406.   if (feof (fp) && buf->used && buf->buf[buf->used - 1] != '\n')
  407.     {
  408.       if (buf->used == buf->alloc)
  409.     {
  410.       buf->alloc *= 2;
  411.       buf->buf = xrealloc (buf->buf, buf->alloc);
  412.     }
  413.       buf->buf[buf->used++] = '\n';
  414.     }
  415.  
  416.   return buf->used;
  417. }
  418.  
  419. /* Initialize LINES, allocating space for ALLOC lines initially.
  420.    LIMIT is the maximum possible number of lines to allocate space
  421.    for, ever.  */
  422.  
  423. static void
  424. initlines (lines, alloc, limit)
  425.      struct lines *lines;
  426.      int alloc;
  427.      int limit;
  428. {
  429.   lines->alloc = alloc;
  430.   lines->lines = (struct line *) xmalloc (lines->alloc * sizeof (struct line));
  431.   lines->used = 0;
  432.   lines->limit = limit;
  433. }
  434.  
  435. /* Return a pointer to the first character of the field specified
  436.    by KEY in LINE. */
  437.  
  438. static char *
  439. begfield (line, key)
  440.      struct line *line;
  441.      struct keyfield *key;
  442. {
  443.   register char *ptr = line->text, *lim = ptr + line->length;
  444.   register int sword = key->sword, schar = key->schar;
  445.  
  446.   if (tab)
  447.     while (ptr < lim && sword--)
  448.       {
  449.     while (ptr < lim && *ptr != tab)
  450.       ++ptr;
  451.     if (ptr < lim)
  452.       ++ptr;
  453.       }
  454.   else
  455.     while (ptr < lim && sword--)
  456.       {
  457.     while (ptr < lim && blanks[UCHAR (*ptr)])
  458.       ++ptr;
  459.     while (ptr < lim && !blanks[UCHAR (*ptr)])
  460.       ++ptr;
  461.       }
  462.  
  463.   if (key->skipsblanks)
  464.     while (ptr < lim && blanks[UCHAR (*ptr)])
  465.       ++ptr;
  466.  
  467.   while (ptr < lim && schar--)
  468.     ++ptr;
  469.  
  470.   return ptr;
  471. }
  472.  
  473. /* Return the limit of (a pointer to the first character after) the field
  474.    in LINE specified by KEY. */
  475.  
  476. static char *
  477. limfield (line, key)
  478.      struct line *line;
  479.      struct keyfield *key;
  480. {
  481.   register char *ptr = line->text, *lim = ptr + line->length;
  482.   register int eword = key->eword, echar = key->echar;
  483.  
  484.   if (tab)
  485.     while (ptr < lim && eword--)
  486.       {
  487.     while (ptr < lim && *ptr != tab)
  488.       ++ptr;
  489.     if (ptr < lim && (eword || key->skipeblanks))
  490.       ++ptr;
  491.       }
  492.   else
  493.     while (ptr < lim && eword--)
  494.       {
  495.     while (ptr < lim && blanks[UCHAR (*ptr)])
  496.       ++ptr;
  497.     while (ptr < lim && !blanks[UCHAR (*ptr)])
  498.       ++ptr;
  499.       }
  500.  
  501.   if (key->skipeblanks)
  502.     while (ptr < lim && blanks[UCHAR (*ptr)])
  503.       ++ptr;
  504.  
  505.   while (ptr < lim && echar--)
  506.     ++ptr;
  507.  
  508.   return ptr;
  509. }
  510.  
  511. /* Find the lines in BUF, storing pointers and lengths in LINES.
  512.    Also replace newlines with NULs. */
  513.  
  514. static void
  515. findlines (buf, lines)
  516.      struct buffer *buf;
  517.      struct lines *lines;
  518. {
  519.   register char *beg = buf->buf, *lim = buf->buf + buf->used, *ptr;
  520.   struct keyfield *key = keyhead.next;
  521.  
  522.   lines->used = 0;
  523.  
  524.   while (beg < lim && (ptr = memchr (beg, '\n', lim - beg))
  525.      && lines->used < lines->limit)
  526.     {
  527.       /* There are various places in the code that rely on a NUL
  528.      being at the end of in-core lines; NULs inside the lines
  529.      will not cause trouble, though. */
  530.       *ptr = '\0';
  531.  
  532.       if (lines->used == lines->alloc)
  533.     {
  534.       lines->alloc *= 2;
  535.       lines->lines = (struct line *)
  536.         xrealloc ((char *) lines->lines,
  537.               lines->alloc * sizeof (struct line));
  538.     }
  539.  
  540.       lines->lines[lines->used].text = beg;
  541.       lines->lines[lines->used].length = ptr - beg;
  542.  
  543.       /* Precompute the position of the first key for efficiency. */
  544.       if (key)
  545.     {
  546.       if (key->eword >= 0)
  547.         lines->lines[lines->used].keylim =
  548.           limfield (&lines->lines[lines->used], key);
  549.       else
  550.         lines->lines[lines->used].keylim = ptr;
  551.  
  552.       if (key->sword >= 0)
  553.         lines->lines[lines->used].keybeg =
  554.           begfield (&lines->lines[lines->used], key);
  555.       else
  556.         {
  557.           if (key->skipsblanks)
  558.         while (blanks[UCHAR (*beg)])
  559.           ++beg;
  560.           lines->lines[lines->used].keybeg = beg;
  561.         }
  562.     }
  563.       else
  564.     {
  565.       lines->lines[lines->used].keybeg = 0;
  566.       lines->lines[lines->used].keylim = 0;
  567.     }
  568.  
  569.       ++lines->used;
  570.       beg = ptr + 1;
  571.     }
  572.  
  573.   buf->left = lim - beg;
  574. }
  575.  
  576. /* Compare strings A and B containing decimal fractions < 1.  Each string
  577.    should begin with a decimal point followed immediately by the digits
  578.    of the fraction.  Strings not of this form are considered to be zero. */
  579.  
  580. static int
  581. fraccompare (a, b)
  582.      register char *a, *b;
  583. {
  584.   register tmpa = UCHAR (*a), tmpb = UCHAR (*b);
  585.  
  586.   if (tmpa == '.' && tmpb == '.')
  587.     {
  588.       do
  589.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  590.       while (tmpa == tmpb && digits[tmpa]);
  591.       if (digits[tmpa] && digits[tmpb])
  592.     return tmpa - tmpb;
  593.       if (digits[tmpa])
  594.     {
  595.       while (tmpa == '0')
  596.         tmpa = UCHAR (*++a);
  597.       if (digits[tmpa])
  598.         return 1;
  599.       return 0;
  600.     }
  601.       if (digits[tmpb])
  602.     {
  603.       while (tmpb == '0')
  604.         tmpb = UCHAR (*++b);
  605.       if (digits[tmpb])
  606.         return -1;
  607.       return 0;
  608.     }
  609.       return 0;
  610.     }
  611.   else if (tmpa == '.')
  612.     {
  613.       do
  614.     tmpa = UCHAR (*++a);
  615.       while (tmpa == '0');
  616.       if (digits[tmpa])
  617.     return 1;
  618.       return 0;
  619.     }
  620.   else if (tmpb == '.')
  621.     {
  622.       do
  623.     tmpb = UCHAR (*++b);
  624.       while (tmpb == '0');
  625.       if (digits[tmpb])
  626.     return -1;
  627.       return 0;
  628.     }
  629.   return 0;
  630. }
  631.  
  632. /* Compare strings A and B as numbers without explicitly converting them to
  633.    machine numbers.  Comparatively slow for short strings, but asymptotically
  634.    hideously fast. */
  635.  
  636. static int
  637. numcompare (a, b)
  638.      register char *a, *b;
  639. {
  640.   register int tmpa, tmpb, loga, logb, tmp;
  641.  
  642.   tmpa = UCHAR (*a), tmpb = UCHAR (*b);
  643.  
  644.   while (blanks[tmpa])
  645.     tmpa = UCHAR (*++a);
  646.   while (blanks[tmpb])
  647.     tmpb = UCHAR (*++b);
  648.  
  649.   if (tmpa == '-')
  650.     {
  651.       tmpa = UCHAR (*++a);
  652.       if (tmpb != '-')
  653.     {
  654.       if (digits[tmpa] && digits[tmpb])
  655.         return -1;
  656.       return 0;
  657.     }
  658.       tmpb = UCHAR (*++b);
  659.  
  660.       while (tmpa == '0')
  661.     tmpa = UCHAR (*++a);
  662.       while (tmpb == '0')
  663.     tmpb = UCHAR (*++b);
  664.  
  665.       while (tmpa == tmpb && digits[tmpa])
  666.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  667.  
  668.       if ((tmpa == '.' && !digits[tmpb]) || (tmpb == '.' && !digits[tmpa]))
  669.     return -fraccompare (a, b);
  670.  
  671.       if (digits[tmpa])
  672.     for (loga = 1; digits[UCHAR (*++a)]; ++loga)
  673.       ;
  674.       else
  675.     loga = 0;
  676.  
  677.       if (digits[tmpb])
  678.     for (logb = 1; digits[UCHAR (*++b)]; ++logb)
  679.       ;
  680.       else
  681.     logb = 0;
  682.  
  683.       if ((tmp = logb - loga) != 0)
  684.     return tmp;
  685.  
  686.       if (!loga)
  687.     return 0;
  688.  
  689.       return tmpb - tmpa;
  690.     }
  691.   else if (tmpb == '-')
  692.     {
  693.       if (digits[UCHAR (tmpa)] && digits[UCHAR (*++b)])
  694.     return 1;
  695.       return 0;
  696.     }
  697.   else
  698.     {
  699.       while (tmpa == '0')
  700.     tmpa = UCHAR (*++a);
  701.       while (tmpb == '0')
  702.     tmpb = UCHAR (*++b);
  703.  
  704.       while (tmpa == tmpb && digits[tmpa])
  705.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  706.  
  707.       if ((tmpa == '.' && !digits[tmpb]) || (tmpb == '.' && !digits[tmpa]))
  708.     return fraccompare (a, b);
  709.  
  710.       if (digits[tmpa])
  711.     for (loga = 1; digits[UCHAR (*++a)]; ++loga)
  712.       ;
  713.       else
  714.     loga = 0;
  715.  
  716.       if (digits[tmpb])
  717.     for (logb = 1; digits[UCHAR (*++b)]; ++logb)
  718.       ;
  719.       else
  720.     logb = 0;
  721.  
  722.       if ((tmp = loga - logb) != 0)
  723.     return tmp;
  724.  
  725.       if (!loga)
  726.     return 0;
  727.  
  728.       return tmpa - tmpb;
  729.     }
  730. }
  731.  
  732. /* Return an integer <= 12 associated with month name S with length LEN,
  733.    0 if the name in S is not recognized. */
  734.  
  735. static int
  736. getmonth (s, len)
  737.      char *s;
  738.      int len;
  739. {
  740.   char month[4];
  741.   register int i, lo = 0, hi = 12;
  742.  
  743.   while (len > 0 && blanks[UCHAR(*s)])
  744.     ++s, --len;
  745.  
  746.   if (len < 3)
  747.     return 0;
  748.  
  749.   for (i = 0; i < 3; ++i)
  750.     month[i] = fold_toupper[UCHAR (s[i])];
  751.   month[3] = '\0';
  752.  
  753.   while (hi - lo > 1)
  754.     if (strcmp (month, monthtab[(lo + hi) / 2].name) < 0)
  755.       hi = (lo + hi) / 2;
  756.     else
  757.       lo = (lo + hi) / 2;
  758.   if (!strcmp (month, monthtab[lo].name))
  759.     return monthtab[lo].val;
  760.   return 0;
  761. }
  762.  
  763. /* Compare two lines A and B trying every key in sequence until there
  764.    are no more keys or a difference is found. */
  765.  
  766. static int
  767. keycompare (a, b)
  768.      struct line *a, *b;
  769. {
  770.   register char *texta, *textb, *lima, *limb, *translate;
  771.   register int *ignore;
  772.   struct keyfield *key;
  773.   int diff = 0, iter = 0, lena, lenb;
  774.  
  775.   for (key = keyhead.next; key; key = key->next, ++iter)
  776.     {
  777.       ignore = key->ignore;
  778.       translate = key->translate;
  779.  
  780.       /* Find the beginning and limit of each field. */
  781.       if (iter || a->keybeg == NULL || b->keybeg == NULL)
  782.     {
  783.       if (key->eword >= 0)
  784.         lima = limfield (a, key), limb = limfield (b, key);
  785.       else
  786.         lima = a->text + a->length, limb = b->text + b->length;
  787.  
  788.       if (key->sword >= 0)
  789.         texta = begfield (a, key), textb = begfield (b, key);
  790.       else
  791.         {
  792.           texta = a->text, textb = b->text;
  793.           if (key->skipsblanks)
  794.         {
  795.           while (texta < lima && blanks[UCHAR (*texta)])
  796.             ++texta;
  797.           while (textb < limb && blanks[UCHAR (*textb)])
  798.             ++textb;
  799.         }
  800.         }
  801.     }
  802.       else
  803.     {
  804.       /* For the first iteration only, the key positions have
  805.          been precomputed for us. */
  806.       texta = a->keybeg, lima = a->keylim;
  807.       textb = b->keybeg, limb = b->keylim;
  808.     }
  809.  
  810.       /* Find the lengths. */
  811.       lena = lima - texta, lenb = limb - textb;
  812.       if (lena < 0)
  813.     lena = 0;
  814.       if (lenb < 0)
  815.     lenb = 0;
  816.  
  817.       /* Actually compare the fields. */
  818.       if (key->numeric)
  819.     {
  820.       if (*lima || *limb)
  821.         {
  822.           char savea = *lima, saveb = *limb;
  823.  
  824.           *lima = *limb = '\0';
  825.           diff = numcompare (texta, textb);
  826.           *lima = savea, *limb = saveb;
  827.         }
  828.       else
  829.         diff = numcompare (texta, textb);
  830.  
  831.       if (diff)
  832.         return key->reverse ? -diff : diff;
  833.       continue;
  834.     }
  835.       else if (key->month)
  836.     {
  837.       diff = getmonth (texta, lena) - getmonth (textb, lenb);
  838.       if (diff)
  839.         return key->reverse ? -diff : diff;
  840.       continue;
  841.     }
  842.       else if (ignore && translate)
  843.     while (texta < lima && textb < limb)
  844.       {
  845.         while (texta < lima && ignore[UCHAR (*texta)])
  846.           ++texta;
  847.         while (textb < limb && ignore[UCHAR (*textb)])
  848.           ++textb;
  849.         if (texta < lima && textb < limb &&
  850.         translate[UCHAR (*texta++)] != translate[UCHAR (*textb++)])
  851.           {
  852.         diff = translate[UCHAR (*--texta)] - translate[UCHAR (*--textb)];
  853.         break;
  854.           }
  855.       }
  856.       else if (ignore)
  857.     while (texta < lima && textb < limb)
  858.       {
  859.         while (texta < lima && ignore[UCHAR (*texta)])
  860.           ++texta;
  861.         while (textb < limb && ignore[UCHAR (*textb)])
  862.           ++textb;
  863.         if (texta < lima && textb < limb && *texta++ != *textb++)
  864.           {
  865.         diff = *--texta - *--textb;
  866.         break;
  867.           }
  868.       }
  869.       else if (translate)
  870.     while (texta < lima && textb < limb)
  871.       {
  872.         if (translate[UCHAR (*texta++)] != translate[UCHAR (*textb++)])
  873.           {
  874.         diff = translate[UCHAR (*--texta)] - translate[UCHAR (*--textb)];
  875.         break;
  876.           }
  877.       }
  878.       else
  879.     diff = memcmp (texta, textb, min (lena, lenb));
  880.  
  881.       if (diff)
  882.     return key->reverse ? -diff : diff;
  883.       if ((diff = lena - lenb) != 0)
  884.     return key->reverse ? -diff : diff;
  885.     }
  886.  
  887.   return 0;
  888. }
  889.  
  890. /* Compare two lines A and B, returning negative, zero, or positive
  891.    depending on whether A compares less than, equal to, or greater than B. */
  892.  
  893. static int
  894. compare (a, b)
  895.      register struct line *a, *b;
  896. {
  897.   int diff, tmpa, tmpb, mini;
  898.  
  899.   /* First try to compare on the specified keys (if any).
  900.      The only two cases with no key at all are unadorned sort,
  901.      and unadorned sort -r. */
  902.   if (keyhead.next)
  903.     {
  904.       diff = keycompare (a, b);
  905.       if (diff != 0)
  906.     return diff;
  907.       if (unique || stable)
  908.     return 0;
  909.     }
  910.  
  911.   /* If the keys all compare equal (or no keys were specified)
  912.      fall through to the default byte-by-byte comparison. */
  913.   tmpa = a->length, tmpb = b->length;
  914.   mini = min (tmpa, tmpb);
  915.   if (mini == 0)
  916.     diff = tmpa - tmpb;
  917.   else
  918.     {
  919.       char *ap = a->text, *bp = b->text;
  920.  
  921.       diff = UCHAR (*ap) - UCHAR (*bp);
  922.       if (diff == 0)
  923.     {
  924.       diff = memcmp (ap, bp, mini);
  925.       if (diff == 0)
  926.         diff = tmpa - tmpb;
  927.     }
  928.     }
  929.  
  930.   return reverse ? -diff : diff;
  931. }
  932.  
  933. /* Check that the lines read from the given FP come in order.  Return
  934.    1 if they do and 0 if there is a disorder. */
  935.  
  936. static int
  937. checkfp (fp)
  938.      FILE *fp;
  939. {
  940.   struct buffer buf;        /* Input buffer. */
  941.   struct lines lines;        /* Lines scanned from the buffer. */
  942.   struct line temp;        /* Copy of previous line. */
  943.   int cc;            /* Character count. */
  944.   int cmp;            /* Result of calling compare. */
  945.   int alloc, i, success = 1;
  946.  
  947.   initbuf (&buf, mergealloc);
  948.   initlines (&lines, mergealloc / linelength + 1,
  949.          LINEALLOC / ((NMERGE + NMERGE) * sizeof (struct line)));
  950.   alloc = linelength;
  951.   temp.text = xmalloc (alloc);
  952.  
  953.   cc = fillbuf (&buf, fp);
  954.   findlines (&buf, &lines);
  955.  
  956.   if (cc)
  957.     do
  958.       {
  959.     /* Compare each line in the buffer with its successor. */
  960.     for (i = 0; i < lines.used - 1; ++i)
  961.       {
  962.         cmp = compare (&lines.lines[i], &lines.lines[i + 1]);
  963.         if ((unique && cmp >= 0) || (cmp > 0))
  964.           {
  965.         success = 0;
  966.         goto finish;
  967.           }
  968.       }
  969.  
  970.     /* Save the last line of the buffer and refill the buffer. */
  971.     if (lines.lines[lines.used - 1].length > alloc)
  972.       {
  973.         while (lines.lines[lines.used - 1].length + 1 > alloc)
  974.           alloc *= 2;
  975.         temp.text = xrealloc (temp.text, alloc);
  976.       }
  977.     bcopy (lines.lines[lines.used - 1].text, temp.text,
  978.            lines.lines[lines.used - 1].length + 1);
  979.     temp.length = lines.lines[lines.used - 1].length;
  980.  
  981.     cc = fillbuf (&buf, fp);
  982.     if (cc)
  983.       {
  984.         findlines (&buf, &lines);
  985.         /* Make sure the line saved from the old buffer contents is
  986.            less than or equal to the first line of the new buffer. */
  987.         cmp = compare (&temp, &lines.lines[0]);
  988.         if ((unique && cmp >= 0) || (cmp > 0))
  989.           {
  990.         success = 0;
  991.         break;
  992.           }
  993.       }
  994.       }
  995.     while (cc);
  996.  
  997. finish:
  998.   xfclose (fp);
  999.   free (buf.buf);
  1000.   free ((char *) lines.lines);
  1001.   free (temp.text);
  1002.   return success;
  1003. }
  1004.  
  1005. /* Merge lines from FPS onto OFP.  NFPS cannot be greater than NMERGE.
  1006.    Close FPS before returning. */
  1007.  
  1008. static void
  1009. mergefps (fps, nfps, ofp)
  1010.      FILE *fps[], *ofp;
  1011.      register int nfps;
  1012. {
  1013.   struct buffer buffer[NMERGE];    /* Input buffers for each file. */
  1014.   struct lines lines[NMERGE];    /* Line tables for each buffer. */
  1015.   struct line saved;        /* Saved line for unique check. */
  1016.   int savedflag = 0;        /* True if there is a saved line. */
  1017.   int savealloc;        /* Size allocated for the saved line. */
  1018.   int cur[NMERGE];        /* Current line in each line table. */
  1019.   int ord[NMERGE];        /* Table representing a permutation of fps,
  1020.                    such that lines[ord[0]].lines[cur[ord[0]]]
  1021.                    is the smallest line and will be next
  1022.                    output. */
  1023.   register int i, j, t;
  1024.  
  1025.   /* Allocate space for a saved line if necessary. */
  1026.   if (unique)
  1027.     {
  1028.       savealloc = linelength;
  1029.       saved.text = xmalloc (savealloc);
  1030.     }
  1031.  
  1032.   /* Read initial lines from each input file. */
  1033.   for (i = 0; i < nfps; ++i)
  1034.     {
  1035.       initbuf (&buffer[i], mergealloc);
  1036.       /* If a file is empty, eliminate it from future consideration. */
  1037.       while (i < nfps && !fillbuf (&buffer[i], fps[i]))
  1038.     {
  1039.       xfclose (fps[i]);
  1040.       --nfps;
  1041.       for (j = i; j < nfps; ++j)
  1042.         fps[j] = fps[j + 1];
  1043.     }
  1044.       if (i == nfps)
  1045.     free (buffer[i].buf);
  1046.       else
  1047.     {
  1048.       initlines (&lines[i], mergealloc / linelength + 1,
  1049.              LINEALLOC / ((NMERGE + NMERGE) * sizeof (struct line)));
  1050.       findlines (&buffer[i], &lines[i]);
  1051.       cur[i] = 0;
  1052.     }
  1053.     }
  1054.  
  1055.   /* Set up the ord table according to comparisons among input lines.
  1056.      Since this only reorders two items if one is strictly greater than
  1057.      the other, it is stable. */
  1058.   for (i = 0; i < nfps; ++i)
  1059.     ord[i] = i;
  1060.   for (i = 1; i < nfps; ++i)
  1061.     if (compare (&lines[ord[i - 1]].lines[cur[ord[i - 1]]],
  1062.          &lines[ord[i]].lines[cur[ord[i]]]) > 0)
  1063.       t = ord[i - 1], ord[i - 1] = ord[i], ord[i] = t, i = 0;
  1064.  
  1065.   /* Repeatedly output the smallest line until no input remains. */
  1066.   while (nfps)
  1067.     {
  1068.       /* If uniqified output is turned out, output only the first of
  1069.      an identical series of lines. */
  1070.       if (unique)
  1071.     {
  1072.       if (savedflag && compare (&saved, &lines[ord[0]].lines[cur[ord[0]]]))
  1073.         {
  1074.           xfwrite (saved.text, 1, saved.length, ofp);
  1075.           putc ('\n', ofp);
  1076.           savedflag = 0;
  1077.         }
  1078.       if (!savedflag)
  1079.         {
  1080.           if (savealloc < lines[ord[0]].lines[cur[ord[0]]].length + 1)
  1081.         {
  1082.           while (savealloc < lines[ord[0]].lines[cur[ord[0]]].length + 1)
  1083.             savealloc *= 2;
  1084.           saved.text = xrealloc (saved.text, savealloc);
  1085.         }
  1086.           saved.length = lines[ord[0]].lines[cur[ord[0]]].length;
  1087.           bcopy (lines[ord[0]].lines[cur[ord[0]]].text, saved.text,
  1088.              saved.length + 1);
  1089.           if (lines[ord[0]].lines[cur[ord[0]]].keybeg != NULL)
  1090.         {
  1091.           saved.keybeg = saved.text +
  1092.             (lines[ord[0]].lines[cur[ord[0]]].keybeg
  1093.              - lines[ord[0]].lines[cur[ord[0]]].text);
  1094.         }
  1095.           if (lines[ord[0]].lines[cur[ord[0]]].keylim != NULL)
  1096.         {
  1097.           saved.keylim = saved.text +
  1098.             (lines[ord[0]].lines[cur[ord[0]]].keylim
  1099.              - lines[ord[0]].lines[cur[ord[0]]].text);
  1100.         }
  1101.           savedflag = 1;
  1102.         }
  1103.     }
  1104.       else
  1105.     {
  1106.       xfwrite (lines[ord[0]].lines[cur[ord[0]]].text, 1,
  1107.            lines[ord[0]].lines[cur[ord[0]]].length, ofp);
  1108.       putc ('\n', ofp);
  1109.     }
  1110.  
  1111.       /* Check if we need to read more lines into core. */
  1112.       if (++cur[ord[0]] == lines[ord[0]].used)
  1113.     if (fillbuf (&buffer[ord[0]], fps[ord[0]]))
  1114.       {
  1115.         findlines (&buffer[ord[0]], &lines[ord[0]]);
  1116.         cur[ord[0]] = 0;
  1117.       }
  1118.     else
  1119.       {
  1120.         /* We reached EOF on fps[ord[0]]. */
  1121.         for (i = 1; i < nfps; ++i)
  1122.           if (ord[i] > ord[0])
  1123.         --ord[i];
  1124.         --nfps;
  1125.         xfclose (fps[ord[0]]);
  1126.         free (buffer[ord[0]].buf);
  1127.         free ((char *) lines[ord[0]].lines);
  1128.         for (i = ord[0]; i < nfps; ++i)
  1129.           {
  1130.         fps[i] = fps[i + 1];
  1131.         buffer[i] = buffer[i + 1];
  1132.         lines[i] = lines[i + 1];
  1133.         cur[i] = cur[i + 1];
  1134.           }
  1135.         for (i = 0; i < nfps; ++i)
  1136.           ord[i] = ord[i + 1];
  1137.         continue;
  1138.       }
  1139.  
  1140.       /* The new line just read in may be larger than other lines
  1141.      already in core; push it back in the queue until we encounter
  1142.      a line larger than it. */
  1143.       for (i = 1; i < nfps; ++i)
  1144.     {
  1145.       t = compare (&lines[ord[0]].lines[cur[ord[0]]],
  1146.                &lines[ord[i]].lines[cur[ord[i]]]);
  1147.       if (!t)
  1148.         t = ord[0] - ord[i];
  1149.       if (t < 0)
  1150.         break;
  1151.     }
  1152.       t = ord[0];
  1153.       for (j = 1; j < i; ++j)
  1154.     ord[j - 1] = ord[j];
  1155.       ord[i - 1] = t;
  1156.     }
  1157.  
  1158.   if (unique && savedflag)
  1159.     {
  1160.       xfwrite (saved.text, 1, saved.length, ofp);
  1161.       putc ('\n', ofp);
  1162.       free (saved.text);
  1163.     }
  1164. }
  1165.  
  1166. /* Sort the array LINES with NLINES members, using TEMP for temporary space. */
  1167.  
  1168. static void
  1169. sortlines (lines, nlines, temp)
  1170.      struct line *lines, *temp;
  1171.      int nlines;
  1172. {
  1173.   register struct line *lo, *hi, *t;
  1174.   register int nlo, nhi;
  1175.  
  1176.   if (nlines == 2)
  1177.     {
  1178.       if (compare (&lines[0], &lines[1]) > 0)
  1179.     *temp = lines[0], lines[0] = lines[1], lines[1] = *temp;
  1180.       return;
  1181.     }
  1182.  
  1183.   nlo = nlines / 2;
  1184.   lo = lines;
  1185.   nhi = nlines - nlo;
  1186.   hi = lines + nlo;
  1187.  
  1188.   if (nlo > 1)
  1189.     sortlines (lo, nlo, temp);
  1190.  
  1191.   if (nhi > 1)
  1192.     sortlines (hi, nhi, temp);
  1193.  
  1194.   t = temp;
  1195.  
  1196.   while (nlo && nhi)
  1197.     if (compare (lo, hi) <= 0)
  1198.       *t++ = *lo++, --nlo;
  1199.     else
  1200.       *t++ = *hi++, --nhi;
  1201.   while (nlo--)
  1202.     *t++ = *lo++;
  1203.  
  1204.   for (lo = lines, nlo = nlines - nhi, t = temp; nlo; --nlo)
  1205.     *lo++ = *t++;
  1206. }
  1207.  
  1208. /* Check that each of the NFILES FILES is ordered.
  1209.    Return a count of disordered files. */
  1210.  
  1211. static int
  1212. check (files, nfiles)
  1213.      char *files[];
  1214.      int nfiles;
  1215. {
  1216.   int i, disorders = 0;
  1217.   FILE *fp;
  1218.  
  1219.   for (i = 0; i < nfiles; ++i)
  1220.     {
  1221.       fp = xfopen (files[i], "r");
  1222.       if (!checkfp (fp))
  1223.     {
  1224.       printf ("%s: disorder on %s\n", program_name, files[i]);
  1225.       ++disorders;
  1226.     }
  1227.     }
  1228.   return disorders;
  1229. }
  1230.  
  1231. /* Merge NFILES FILES onto OFP. */
  1232.  
  1233. static void
  1234. merge (files, nfiles, ofp)
  1235.      char *files[];
  1236.      int nfiles;
  1237.      FILE *ofp;
  1238. {
  1239.   int i, j, t;
  1240.   char *temp;
  1241.   FILE *fps[NMERGE], *tfp;
  1242.  
  1243.   while (nfiles > NMERGE)
  1244.     {
  1245.       t = 0;
  1246.       for (i = 0; i < nfiles / NMERGE; ++i)
  1247.     {
  1248.       for (j = 0; j < NMERGE; ++j)
  1249.         fps[j] = xfopen (files[i * NMERGE + j], "r");
  1250.       tfp = xfopen (temp = tempname (), "w");
  1251.       mergefps (fps, NMERGE, tfp);
  1252.       xfclose (tfp);
  1253.       for (j = 0; j < NMERGE; ++j)
  1254.         zaptemp (files[i * NMERGE + j]);
  1255.       files[t++] = temp;
  1256.     }
  1257.       for (j = 0; j < nfiles % NMERGE; ++j)
  1258.     fps[j] = xfopen (files[i * NMERGE + j], "r");
  1259.       tfp = xfopen (temp = tempname (), "w");
  1260.       mergefps (fps, nfiles % NMERGE, tfp);
  1261.       xfclose (tfp);
  1262.       for (j = 0; j < nfiles % NMERGE; ++j)
  1263.     zaptemp (files[i * NMERGE + j]);
  1264.       files[t++] = temp;
  1265.       nfiles = t;
  1266.     }
  1267.  
  1268.   for (i = 0; i < nfiles; ++i)
  1269.     fps[i] = xfopen (files[i], "r");
  1270.   mergefps (fps, i, ofp);
  1271.   for (i = 0; i < nfiles; ++i)
  1272.     zaptemp (files[i]);
  1273. }
  1274.  
  1275. /* Sort NFILES FILES onto OFP. */
  1276.  
  1277. static void
  1278. sort (files, nfiles, ofp)
  1279.      char **files;
  1280.      int nfiles;
  1281.      FILE *ofp;
  1282. {
  1283.   struct buffer buf;
  1284.   struct lines lines;
  1285.   struct line *tmp;
  1286.   int i, ntmp;
  1287.   FILE *fp, *tfp;
  1288.   struct tempnode *node;
  1289.   int ntemp = 0;
  1290.   char **tempfiles;
  1291.  
  1292.   initbuf (&buf, sortalloc);
  1293.   initlines (&lines, sortalloc / linelength + 1,
  1294.          LINEALLOC / sizeof (struct line));
  1295.   ntmp = lines.alloc;
  1296.   tmp = (struct line *) xmalloc (ntmp * sizeof (struct line));
  1297.  
  1298.   while (nfiles--)
  1299.     {
  1300.       fp = xfopen (*files++, "r");
  1301.       while (fillbuf (&buf, fp))
  1302.     {
  1303.       findlines (&buf, &lines);
  1304.       if (lines.used > ntmp)
  1305.         {
  1306.           while (lines.used > ntmp)
  1307.         ntmp *= 2;
  1308.           tmp = (struct line *)
  1309.         xrealloc ((char *) tmp, ntmp * sizeof (struct line));
  1310.         }
  1311.       sortlines (lines.lines, lines.used, tmp);
  1312.       if (feof (fp) && !nfiles && !ntemp && !buf.left)
  1313.         tfp = ofp;
  1314.       else
  1315.         {
  1316.           ++ntemp;
  1317.           tfp = xfopen (tempname (), "w");
  1318.         }
  1319.       for (i = 0; i < lines.used; ++i)
  1320.         if (!unique || i == 0
  1321.         || compare (&lines.lines[i], &lines.lines[i - 1]))
  1322.           {
  1323.         xfwrite (lines.lines[i].text, 1, lines.lines[i].length, tfp);
  1324.         putc ('\n', tfp);
  1325.           }
  1326.       if (tfp != ofp)
  1327.         xfclose (tfp);
  1328.     }
  1329.       xfclose (fp);
  1330.     }
  1331.  
  1332.   free (buf.buf);
  1333.   free ((char *) lines.lines);
  1334.   free ((char *) tmp);
  1335.  
  1336.   if (ntemp)
  1337.     {
  1338.       tempfiles = (char **) xmalloc (ntemp * sizeof (char *));
  1339.       i = ntemp;
  1340.       for (node = temphead.next; i > 0; node = node->next)
  1341.     tempfiles[--i] = node->name;
  1342.       merge (tempfiles, ntemp, ofp);
  1343.       free ((char *) tempfiles);
  1344.     }
  1345. }
  1346.  
  1347. /* Insert key KEY at the end of the list (`keyhead'). */
  1348.  
  1349. static void
  1350. insertkey (key)
  1351.      struct keyfield *key;
  1352. {
  1353.   struct keyfield *k = &keyhead;
  1354.  
  1355.   while (k->next)
  1356.     k = k->next;
  1357.   k->next = key;
  1358.   key->next = NULL;
  1359. }
  1360.  
  1361. static void
  1362. badfieldspec (s)
  1363.      char *s;
  1364. {
  1365.   error (2, 0, "invalid field specification `%s'", s);
  1366. }
  1367.  
  1368. /* Handle interrupts and hangups. */
  1369.  
  1370. static void
  1371. sighandler (sig)
  1372.      int sig;
  1373. {
  1374. #ifdef _POSIX_VERSION
  1375.   struct sigaction sigact;
  1376.  
  1377.   sigact.sa_handler = SIG_DFL;
  1378.   sigemptyset (&sigact.sa_mask);
  1379.   sigact.sa_flags = 0;
  1380.   sigaction (sig, &sigact, NULL);
  1381. #else                /* !_POSIX_VERSION */
  1382.   signal (sig, SIG_DFL);
  1383. #endif                /* _POSIX_VERSION */
  1384.   cleanup ();
  1385.   kill (getpid (), sig);
  1386. }
  1387.  
  1388. /* Set the ordering options for KEY specified in S.
  1389.    Return the address of the first character in S that
  1390.    is not a valid ordering option.
  1391.    BLANKTYPE is the kind of blanks that 'b' should skip. */
  1392.  
  1393. static char *
  1394. set_ordering (s, key, blanktype)
  1395.      register char *s;
  1396.      struct keyfield *key;
  1397.      enum blanktype blanktype;
  1398. {
  1399.   while (*s)
  1400.     {
  1401.       switch (*s)
  1402.     {
  1403.     case 'b':
  1404.       if (blanktype == bl_start || blanktype == bl_both)
  1405.         key->skipsblanks = 1;
  1406.       if (blanktype == bl_end || blanktype == bl_both)
  1407.         key->skipeblanks = 1;
  1408.       break;
  1409.     case 'd':
  1410.       key->ignore = nondictionary;
  1411.       break;
  1412.     case 'f':
  1413.       key->translate = fold_toupper;
  1414.       break;
  1415. #if 0
  1416.     case 'g':
  1417.       /* Reserved for comparing floating-point numbers. */
  1418.       break;
  1419. #endif
  1420.     case 'i':
  1421.       key->ignore = nonprinting;
  1422.       break;
  1423.     case 'M':
  1424.       key->month = 1;
  1425.       break;
  1426.     case 'n':
  1427.       key->numeric = 1;
  1428.       break;
  1429.     case 'r':
  1430.       key->reverse = 1;
  1431.       break;
  1432.     default:
  1433.       return s;
  1434.     }
  1435.       ++s;
  1436.     }
  1437.   return s;
  1438. }
  1439.  
  1440. main (argc, argv)
  1441.      int argc;
  1442.      char *argv[];
  1443. {
  1444.   struct keyfield *key = NULL, gkey;
  1445.   char *s;
  1446.   int i, t, t2;
  1447.   int checkonly = 0, mergeonly = 0, nfiles = 0;
  1448.   char *minus = "-", *outfile = minus, **files, *tmp;
  1449.   FILE *ofp;
  1450. #ifdef _POSIX_VERSION
  1451.   struct sigaction oldact, newact;
  1452. #endif                /* _POSIX_VERSION */
  1453.  
  1454.   program_name = argv[0];
  1455.  
  1456.   parse_long_options (argc, argv, "sort", version_string, usage);
  1457.  
  1458.   have_read_stdin = 0;
  1459.   inittables ();
  1460.  
  1461.   temp_file_prefix = getenv ("TMPDIR");
  1462.   if (temp_file_prefix == NULL)
  1463.     temp_file_prefix = "/tmp";
  1464.  
  1465. #ifdef _POSIX_VERSION
  1466.   newact.sa_handler = sighandler;
  1467.   sigemptyset (&newact.sa_mask);
  1468.   newact.sa_flags = 0;
  1469.  
  1470.   sigaction (SIGINT, NULL, &oldact);
  1471.   if (oldact.sa_handler != SIG_IGN)
  1472.     sigaction (SIGINT, &newact, NULL);
  1473.   sigaction (SIGHUP, NULL, &oldact);
  1474.   if (oldact.sa_handler != SIG_IGN)
  1475.     sigaction (SIGHUP, &newact, NULL);
  1476.   sigaction (SIGPIPE, NULL, &oldact);
  1477.   if (oldact.sa_handler != SIG_IGN)
  1478.     sigaction (SIGPIPE, &newact, NULL);
  1479.   sigaction (SIGTERM, NULL, &oldact);
  1480.   if (oldact.sa_handler != SIG_IGN)
  1481.     sigaction (SIGTERM, &newact, NULL);
  1482. #else                /* !_POSIX_VERSION */
  1483.   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
  1484.     signal (SIGINT, sighandler);
  1485.   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
  1486.     signal (SIGHUP, sighandler);
  1487.   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
  1488.     signal (SIGPIPE, sighandler);
  1489.   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
  1490.     signal (SIGTERM, sighandler);
  1491. #endif                /* !_POSIX_VERSION */
  1492.  
  1493.   gkey.sword = gkey.eword = -1;
  1494.   gkey.ignore = NULL;
  1495.   gkey.translate = NULL;
  1496.   gkey.numeric = gkey.month = gkey.reverse = 0;
  1497.   gkey.skipsblanks = gkey.skipeblanks = 0;
  1498.  
  1499.   files = (char **) xmalloc (sizeof (char *) * argc);
  1500.  
  1501.   for (i = 1; i < argc; ++i)
  1502.     {
  1503.       if (argv[i][0] == '+')
  1504.     {
  1505.       if (key)
  1506.         insertkey (key);
  1507.       key = (struct keyfield *) xmalloc (sizeof (struct keyfield));
  1508.       key->eword = -1;
  1509.       key->ignore = NULL;
  1510.       key->translate = NULL;
  1511.       key->skipsblanks = key->skipeblanks = 0;
  1512.       key->numeric = key->month = key->reverse = 0;
  1513.       s = argv[i] + 1;
  1514.       if (!digits[UCHAR (*s)])
  1515.         badfieldspec (argv[i]);
  1516.       for (t = 0; digits[UCHAR (*s)]; ++s)
  1517.         t = 10 * t + *s - '0';
  1518.       t2 = 0;
  1519.       if (*s == '.')
  1520.         for (++s; digits[UCHAR (*s)]; ++s)
  1521.           t2 = 10 * t2 + *s - '0';
  1522.       if (t2 || t)
  1523.         {
  1524.           key->sword = t;
  1525.           key->schar = t2;
  1526.         }
  1527.       else
  1528.         key->sword = -1;
  1529.       s = set_ordering (s, key, bl_start);
  1530.       if (*s)
  1531.         badfieldspec (argv[i]);
  1532.     }
  1533.       else if (argv[i][0] == '-' && argv[i][1])
  1534.     {
  1535.       s = argv[i] + 1;
  1536.       if (digits[UCHAR (*s)])
  1537.         {
  1538.           if (!key)
  1539.         usage (2);
  1540.           for (t = 0; digits[UCHAR (*s)]; ++s)
  1541.         t = t * 10 + *s - '0';
  1542.           t2 = 0;
  1543.           if (*s == '.')
  1544.         for (++s; digits[UCHAR (*s)]; ++s)
  1545.           t2 = t2 * 10 + *s - '0';
  1546.           key->eword = t;
  1547.           key->echar = t2;
  1548.           s = set_ordering (s, key, bl_end);
  1549.           if (*s)
  1550.         badfieldspec (argv[i]);
  1551.           insertkey (key);
  1552.           key = NULL;
  1553.         }
  1554.       else
  1555.         while (*s)
  1556.           {
  1557.         s = set_ordering (s, &gkey, bl_both);
  1558.         switch (*s)
  1559.           {
  1560.           case '\0':
  1561.             break;
  1562.           case 'c':
  1563.             checkonly = 1;
  1564.             break;
  1565.           case 'k':
  1566.             if (s[1])
  1567.               ++s;
  1568.             else
  1569.               {
  1570.             if (i == argc - 1)
  1571.               error (2, 0, "option `-k' requires an argument");
  1572.             else
  1573.               s = argv[++i];
  1574.               }
  1575.             if (key)
  1576.               insertkey (key);
  1577.             key = (struct keyfield *)
  1578.               xmalloc (sizeof (struct keyfield));
  1579.             key->eword = -1;
  1580.             key->ignore = NULL;
  1581.             key->translate = NULL;
  1582.             key->skipsblanks = key->skipeblanks = 0;
  1583.             key->numeric = key->month = key->reverse = 0;
  1584.             /* Get POS1. */
  1585.             if (!digits[UCHAR (*s)])
  1586.               badfieldspec (argv[i]);
  1587.             for (t = 0; digits[UCHAR (*s)]; ++s)
  1588.               t = 10 * t + *s - '0';
  1589.             if (t)
  1590.               t--;
  1591.             t2 = 0;
  1592.             if (*s == '.')
  1593.               {
  1594.             for (++s; digits[UCHAR (*s)]; ++s)
  1595.               t2 = 10 * t2 + *s - '0';
  1596.             if (t2)
  1597.               t2--;
  1598.               }
  1599.             if (t2 || t)
  1600.               {
  1601.             key->sword = t;
  1602.             key->schar = t2;
  1603.               }
  1604.             else
  1605.               key->sword = -1;
  1606.             s = set_ordering (s, key, bl_start);
  1607.             if (*s && *s != ',')
  1608.               badfieldspec (argv[i]);
  1609.             else if (*s++)
  1610.               {
  1611.             /* Get POS2. */
  1612.             for (t = 0; digits[UCHAR (*s)]; ++s)
  1613.               t = t * 10 + *s - '0';
  1614.             t2 = 0;
  1615.             if (*s == '.')
  1616.               {
  1617.                 for (++s; digits[UCHAR (*s)]; ++s)
  1618.                   t2 = t2 * 10 + *s - '0';
  1619.                 if (t2)
  1620.                   t--;
  1621.               }
  1622.             key->eword = t;
  1623.             key->echar = t2;
  1624.             s = set_ordering (s, key, bl_end);
  1625.             if (*s)
  1626.               badfieldspec (argv[i]);
  1627.               }
  1628.             insertkey (key);
  1629.             key = NULL;
  1630.             goto outer;
  1631.           case 'm':
  1632.             mergeonly = 1;
  1633.             break;
  1634.           case 'o':
  1635.             if (s[1])
  1636.               outfile = s + 1;
  1637.             else
  1638.               {
  1639.             if (i == argc - 1)
  1640.               error (2, 0, "option `-o' requires an argument");
  1641.             else
  1642.               outfile = argv[++i];
  1643.               }
  1644.             goto outer;
  1645.           case 's':
  1646.             stable = 1;
  1647.             break;
  1648.           case 't':
  1649.             if (s[1])
  1650.               tab = *++s;
  1651.             else if (i < argc - 1)
  1652.               {
  1653.             tab = *argv[++i];
  1654.             goto outer;
  1655.               }
  1656.             else
  1657.               error (2, 0, "option `-t' requires an argument");
  1658.             break;
  1659.           case 'T':
  1660.             if (s[1])
  1661.               temp_file_prefix = ++s;
  1662.             else
  1663.               {
  1664.             if (i < argc - 1)
  1665.               temp_file_prefix = argv[++i];
  1666.             else
  1667.               error (2, 0, "option `-T' requires an argument");
  1668.               }
  1669.             goto outer;
  1670.             break;
  1671.           case 'u':
  1672.             unique = 1;
  1673.             break;
  1674.           case 'y':
  1675.             /* Accept and ignore e.g. -y0 for compatibility with
  1676.                Solaris 2.  */
  1677.             goto outer;
  1678.           default:
  1679.             fprintf (stderr, "%s: unrecognized option `-%c'\n",
  1680.                  argv[0], *s);
  1681.             usage (2);
  1682.           }
  1683.         if (*s)
  1684.           ++s;
  1685.           }
  1686.     }
  1687.       else            /* Not an option. */
  1688.     {
  1689.       files[nfiles++] = argv[i];
  1690.     }
  1691.     outer:;
  1692.     }
  1693.  
  1694.   if (key)
  1695.     insertkey (key);
  1696.  
  1697.   /* Inheritance of global options to individual keys. */
  1698.   for (key = keyhead.next; key; key = key->next)
  1699.     if (!key->ignore && !key->translate && !key->skipsblanks && !key->reverse
  1700.     && !key->skipeblanks && !key->month && !key->numeric)
  1701.       {
  1702.     key->ignore = gkey.ignore;
  1703.     key->translate = gkey.translate;
  1704.     key->skipsblanks = gkey.skipsblanks;
  1705.     key->skipeblanks = gkey.skipeblanks;
  1706.     key->month = gkey.month;
  1707.     key->numeric = gkey.numeric;
  1708.     key->reverse = gkey.reverse;
  1709.       }
  1710.  
  1711.   if (!keyhead.next && (gkey.ignore || gkey.translate || gkey.skipsblanks
  1712.             || gkey.skipeblanks || gkey.month || gkey.numeric))
  1713.     insertkey (&gkey);
  1714.   reverse = gkey.reverse;
  1715.  
  1716.   if (nfiles == 0)
  1717.     {
  1718.       nfiles = 1;
  1719.       files = −
  1720.     }
  1721.  
  1722.   if (checkonly)
  1723.     exit (check (files, nfiles) != 0);
  1724.  
  1725.   if (strcmp (outfile, "-"))
  1726.     {
  1727.       struct stat outstat;
  1728.       if (SAFE_STAT (outfile, &outstat) == 0)
  1729.     {
  1730.       /* The following code prevents a race condition when
  1731.          people use the brain dead shell programming idiom:
  1732.           cat file | sort -o file
  1733.          This feature is provided for historical compatibility,
  1734.          but we strongly discourage ever relying on this in
  1735.          new shell programs. */
  1736.  
  1737.       /* Temporarily copy each input file that might be another name
  1738.          for the output file.  When in doubt (e.g. a pipe), copy.  */
  1739.       for (i = 0; i < nfiles; ++i)
  1740.         {
  1741.           char buf[8192];
  1742.           FILE *fp;
  1743.           int cc;
  1744.  
  1745.           if (S_ISREG (outstat.st_mode) && strcmp (outfile, files[i]))
  1746.         {
  1747.           struct stat instat;
  1748.           if ((strcmp (files[i], "-")
  1749.                ? SAFE_STAT (files[i], &instat)
  1750.                : fstat (fileno (stdin), &instat)) != 0)
  1751.             {
  1752.               error (0, errno, "%s", files[i]);
  1753.               cleanup ();
  1754.               exit (2);
  1755.             }
  1756.           if (S_ISREG (instat.st_mode)
  1757.               && (instat.st_ino != outstat.st_ino
  1758.               || instat.st_dev != outstat.st_dev))
  1759.             {
  1760.               /* We know the files are distinct.  */
  1761.               continue;
  1762.             }
  1763.         }
  1764.  
  1765.           fp = xfopen (files[i], "r");
  1766.           tmp = tempname ();
  1767.           ofp = xfopen (tmp, "w");
  1768.           while ((cc = fread (buf, 1, sizeof buf, fp)) > 0)
  1769.         xfwrite (buf, 1, cc, ofp);
  1770.           if (ferror (fp))
  1771.         {
  1772.           error (0, errno, "%s", files[i]);
  1773.           cleanup ();
  1774.           exit (2);
  1775.         }
  1776.           xfclose (ofp);
  1777.           xfclose (fp);
  1778.           files[i] = tmp;
  1779.         }
  1780.     }
  1781.       ofp = xfopen (outfile, "w");
  1782.     }
  1783.   else
  1784.     ofp = stdout;
  1785.  
  1786.   if (mergeonly)
  1787.     merge (files, nfiles, ofp);
  1788.   else
  1789.     sort (files, nfiles, ofp);
  1790.   cleanup ();
  1791.  
  1792.   /* If we wait for the implicit flush on exit, and the parent process
  1793.      has closed stdout (e.g., exec >&- in a shell), then the output file
  1794.      winds up empty.  I don't understand why.  This is under SunOS,
  1795.      Solaris, Ultrix, and Irix.  This premature fflush makes the output
  1796.      reappear. --karl@cs.umb.edu  */
  1797.   if (fflush (ofp) < 0)
  1798.     error (1, errno, "fflush", outfile);
  1799.  
  1800.   if (have_read_stdin && fclose (stdin) == EOF)
  1801.     error (1, errno, "-");
  1802.   if (ferror (stdout) || fclose (stdout) == EOF)
  1803.     error (1, errno, "write error");
  1804.  
  1805.   exit (0);
  1806. }
  1807.  
  1808. static void
  1809. usage (status)
  1810.      int status;
  1811. {
  1812.   if (status != 0)
  1813.     fprintf (stderr, "Try `%s --help' for more information.\n",
  1814.          program_name);
  1815.   else
  1816.     {
  1817.       printf ("\
  1818. Usage: %s [OPTION]... [FILE]...\n\
  1819. ",
  1820.           program_name);
  1821.       printf ("\
  1822. \n\
  1823.   +POS1 [-POS2]    start a key at POS1, end it before POS2\n\
  1824.   -M               compare (unknown) < `JAN' < ... < `DEC', imply -b\n\
  1825.   -T DIRECT        use DIRECT for temporary files, not $TMPDIR or /tmp\n\
  1826.   -b               ignore leading blanks in sort fields or keys\n\
  1827.   -c               check if given files already sorted, do not sort\n\
  1828.   -d               consider only [a-zA-Z0-9 ] characters in keys\n\
  1829.   -f               fold lower case to upper case characters in keys\n\
  1830.   -i               consider only [\\040-\\0176] characters in keys\n\
  1831.   -k POS1[,POS2]   same as +POS1 [-POS2], but all positions counted from 1\n\
  1832.   -m               merge already sorted files, do not sort\n\
  1833.   -n               compare according to string numerical value, imply -b\n\
  1834.   -o FILE          write result on FILE instead of standard output\n\
  1835.   -r               reverse the result of comparisons\n\
  1836.   -s               stabilize sort by disabling last resort comparison\n\
  1837.   -t SEP           use SEParator instead of non- to whitespace transition\n\
  1838.   -u               with -c, check for strict ordering\n\
  1839.   -u               with -m, only output the first of an equal sequence\n\
  1840.       --help       display this help and exit\n\
  1841.       --version    output version information and exit\n\
  1842. \n\
  1843. POS is F[.C][OPTS], where F is the field number and C the character\n\
  1844. position in the field, both counted from zero.  OPTS is made up of one\n\
  1845. or more of Mbdfinr, this effectively disable global -Mbdfinr settings\n\
  1846. for that key.  If no key given, use the entire line as key.  With no\n\
  1847. FILE, or when FILE is -, read standard input.\n\
  1848. ");
  1849.     }
  1850.   exit (status);
  1851. }
  1852.