home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / txtut122.zip / textutil / src / join.c < prev    next >
C/C++ Source or Header  |  1998-04-11  |  22KB  |  902 lines

  1. /* join - join lines of two files on a common field
  2.    Copyright (C) 91, 95, 1996 Free Software Foundation, Inc.
  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 Foundation,
  16.    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  17.  
  18.    Written by Mike Haertel, mike@gnu.ai.mit.edu.  */
  19.  
  20. #include <config.h>
  21.  
  22. #ifdef __GNUC__
  23. #define alloca __builtin_alloca
  24. #else /* not __GNUC__ */
  25. #if HAVE_ALLOCA_H
  26. #include <alloca.h>
  27. #else /* not HAVE_ALLOCA_H */
  28. #ifdef _AIX
  29.  #pragma alloca
  30. #else /* not _AIX */
  31. char *alloca ();
  32. #endif /* not _AIX */
  33. #endif /* not HAVE_ALLOCA_H */
  34. #endif /* not __GNUC__ */
  35.  
  36. /* Get isblank from GNU libc.  */
  37. #define _GNU_SOURCE
  38.  
  39. #include <stdio.h>
  40. #define NDEBUG
  41. #include <assert.h>
  42. #include <sys/types.h>
  43. #include <getopt.h>
  44.  
  45. #if HAVE_LIMITS_H
  46. # include <limits.h>
  47. #endif
  48.  
  49. #ifndef UINT_MAX
  50. # define UINT_MAX ((unsigned int) ~(unsigned int) 0)
  51. #endif
  52.  
  53. #ifndef INT_MAX
  54. # define INT_MAX ((int) (UINT_MAX >> 1))
  55. #endif
  56.  
  57. #if _LIBC || STDC_HEADERS
  58. # define TOLOWER(c) tolower (c)
  59. #else
  60. # define TOLOWER(c) (ISUPPER (c) ? tolower (c) : (c))
  61. #endif
  62.  
  63. #include "system.h"
  64. #include "long-options.h"
  65. #include "xstrtol.h"
  66. #include "error.h"
  67. #include "memcasecmp.h"
  68.  
  69. #define join system_join
  70.  
  71. char *xmalloc ();
  72. char *xrealloc ();
  73.  
  74. /* Undefine, to avoid warning about redefinition on some systems.  */
  75. #undef min
  76. #undef max
  77. #define min(A, B) ((A) < (B) ? (A) : (B))
  78. #define max(A, B) ((A) > (B) ? (A) : (B))
  79.  
  80. /* An element of the list identifying which fields to print for each
  81.    output line.  */
  82. struct outlist
  83.   {
  84.     /* File number: 0, 1, or 2.  0 means use the join field.
  85.        1 means use the first file argument, 2 the second.  */
  86.     int file;
  87.  
  88.     /* Field index (zero-based), specified only when FILE is 1 or 2.  */
  89.     int field;
  90.  
  91.     struct outlist *next;
  92.   };
  93.  
  94. /* A field of a line.  */
  95. struct field
  96.   {
  97.     const char *beg;        /* First character in field.  */
  98.     size_t len;            /* The length of the field.  */
  99.   };
  100.  
  101. /* A line read from an input file.  Newlines are not stored.  */
  102. struct line
  103.   {
  104.     char *beg;            /* First character in line.  */
  105.     char *lim;            /* Character after last character in line.  */
  106.     int nfields;        /* Number of elements in `fields'.  */
  107.     int nfields_allocated;    /* Number of elements in `fields'.  */
  108.     struct field *fields;
  109.   };
  110.  
  111. /* One or more consecutive lines read from a file that all have the
  112.    same join field value.  */
  113. struct seq
  114.   {
  115.     int count;            /* Elements used in `lines'.  */
  116.     int alloc;            /* Elements allocated in `lines'.  */
  117.     struct line *lines;
  118.   };
  119.  
  120. /* The name this program was run with.  */
  121. char *program_name;
  122.  
  123. /* If nonzero, print unpairable lines in file 1 or 2.  */
  124. static int print_unpairables_1, print_unpairables_2;
  125.  
  126. /* If nonzero, print pairable lines.  */
  127. static int print_pairables;
  128.  
  129. /* Empty output field filler.  */
  130. static char *empty_filler;
  131.  
  132. /* Field to join on.  */
  133. static int join_field_1, join_field_2;
  134.  
  135. /* List of fields to print.  */
  136. static struct outlist outlist_head;
  137.  
  138. /* Last element in `outlist', where a new element can be added.  */
  139. static struct outlist *outlist_end = &outlist_head;
  140.  
  141. /* Tab character separating fields; if this is NUL fields are separated
  142.    by any nonempty string of white space, otherwise by exactly one
  143.    tab character.  */
  144. static char tab;
  145.  
  146. /* When using getopt_long_only, no long option can start with
  147.    a character that is a short option.  */
  148. static struct option const longopts[] =
  149. {
  150.   {"ignore-case", no_argument, NULL, 'i'},
  151.   {"j", required_argument, NULL, 'j'},
  152.   {"j1", required_argument, NULL, '1'},
  153.   {"j2", required_argument, NULL, '2'},
  154.   {NULL, 0, NULL, 0}
  155. };
  156.  
  157. /* Used to print non-joining lines */
  158. static struct line uni_blank;
  159.  
  160. /* If nonzero, ignore case when comparing join fields.  */
  161. static int ignore_case;
  162.  
  163. static void
  164. usage (int status)
  165. {
  166.   if (status != 0)
  167.     fprintf (stderr, _("Try `%s --help' for more information.\n"),
  168.          program_name);
  169.   else
  170.     {
  171.       printf (_("\
  172. Usage: %s [OPTION]... FILE1 FILE2\n\
  173. "),
  174.           program_name);
  175.       printf (_("\
  176. For each pair of input lines with identical join fields, write a line to\n\
  177. standard output.  The default join field is the first, delimited\n\
  178. by whitespace.  When FILE1 or FILE2 (not both) is -, read standard input.\n\
  179. \n\
  180.   -a SIDE           print unpairable lines coming from file SIDE\n\
  181.   -e EMPTY          replace missing input fields with EMPTY\n\
  182.   -i, --ignore-case ignore differences in case when comparing fields\n\
  183.   -j FIELD          (obsolescent) equivalent to `-1 FIELD -2 FIELD'\n\
  184.   -j1 FIELD         (obsolescent) equivalent to `-1 FIELD'\n\
  185.   -j2 FIELD         (obsolescent) equivalent to `-2 FIELD'\n\
  186.   -o FORMAT         obey FORMAT while constructing output line\n\
  187.   -t CHAR           use CHAR as input and output field separator\n\
  188.   -v SIDE           like -a SIDE, but suppress joined output lines\n\
  189.   -1 FIELD          join on this FIELD of file 1\n\
  190.   -2 FIELD          join on this FIELD of file 2\n\
  191.       --help        display this help and exit\n\
  192.       --version     output version information and exit\n\
  193. \n\
  194. Unless -t CHAR is given, leading blanks separate fields and are ignored,\n\
  195. else fields are separated by CHAR.  Any FIELD is a field number counted\n\
  196. from 1.  FORMAT is one or more comma or blank separated specifications,\n\
  197. each being `SIDE.FIELD' or `0'.  Default FORMAT outputs the join field,\n\
  198. the remaining fields from FILE1, the remaining fields from FILE2, all\n\
  199. separated by CHAR.\n\
  200. "));
  201.       puts (_("\nReport bugs to textutils-bugs@gnu.ai.mit.edu"));
  202.     }
  203.   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
  204. }
  205.  
  206. static void
  207. ADD_FIELD (struct line *line, const char *field, size_t len)
  208. {
  209.   if (line->nfields >= line->nfields_allocated)
  210.     {
  211.       line->nfields_allocated = (3 * line->nfields_allocated) / 2 + 1;
  212.       line->fields = (struct field *) xrealloc ((char *) line->fields,
  213.                         (line->nfields_allocated
  214.                          * sizeof (struct field)));
  215.     }
  216.   line->fields[line->nfields].beg = field;
  217.   line->fields[line->nfields].len = len;
  218.   ++(line->nfields);
  219. }
  220.  
  221. /* Fill in the `fields' structure in LINE.  */
  222.  
  223. static void
  224. xfields (struct line *line)
  225. {
  226.   int i;
  227.   register char *ptr, *lim;
  228.  
  229.   ptr = line->beg;
  230.   lim = line->lim;
  231.  
  232.   if (!tab)
  233.     {
  234.       /* Skip leading blanks before the first field.  */
  235.       while (ptr < lim && ISSPACE (*ptr))
  236.     ++ptr;
  237.     }
  238.  
  239.   for (i = 0; ptr < lim; ++i)
  240.     {
  241.       if (tab)
  242.     {
  243.       char *beg;
  244.  
  245.       beg = ptr;
  246.       while (ptr < lim && *ptr != tab)
  247.         ++ptr;
  248.       ADD_FIELD (line, beg, ptr - beg);
  249.       if (ptr < lim)
  250.         ++ptr;
  251.     }
  252.       else
  253.     {
  254.       char *beg;
  255.  
  256.       beg = ptr;
  257.       while (ptr < lim && !ISSPACE (*ptr))
  258.         ++ptr;
  259.       ADD_FIELD (line, beg, ptr - beg);
  260.       while (ptr < lim && ISSPACE (*ptr))
  261.         ++ptr;
  262.     }
  263.     }
  264.  
  265.   if (ptr > line->beg && ((tab && ISSPACE (ptr[-1])) || ptr[-1] == tab))
  266.     {
  267.       /* Add one more (empty) field because the last character of the
  268.      line was a delimiter.  */
  269.       ADD_FIELD (line, NULL, 0);
  270.     }
  271. }
  272.  
  273. /* Read a line from FP into LINE and split it into fields.
  274.    Return 0 if EOF, 1 otherwise.  */
  275.  
  276. static int
  277. get_line (FILE *fp, struct line *line)
  278. {
  279.   static int linesize = 80;
  280.   int c, i;
  281.   char *ptr;
  282.  
  283.   if (feof (fp))
  284.     return 0;
  285.  
  286.   ptr = xmalloc (linesize);
  287.  
  288.   for (i = 0; (c = getc (fp)) != EOF && c != '\n'; ++i)
  289.     {
  290.       if (i == linesize)
  291.     {
  292.       linesize *= 2;
  293.       ptr = xrealloc (ptr, linesize);
  294.     }
  295.       ptr[i] = c;
  296.     }
  297.  
  298.   if (c == EOF && i == 0)
  299.     {
  300.       free (ptr);
  301.       return 0;
  302.     }
  303.  
  304.   line->beg = ptr;
  305.   line->lim = line->beg + i;
  306.   line->nfields_allocated = 0;
  307.   line->nfields = 0;
  308.   line->fields = NULL;
  309.   xfields (line);
  310.   return 1;
  311. }
  312.  
  313. static void
  314. freeline (struct line *line)
  315. {
  316.   free ((char *) line->fields);
  317.   free (line->beg);
  318.   line->beg = NULL;
  319. }
  320.  
  321. static void
  322. initseq (struct seq *seq)
  323. {
  324.   seq->count = 0;
  325.   seq->alloc = 1;
  326.   seq->lines = (struct line *) xmalloc (seq->alloc * sizeof (struct line));
  327. }
  328.  
  329. /* Read a line from FP and add it to SEQ.  Return 0 if EOF, 1 otherwise.  */
  330.  
  331. static int
  332. getseq (FILE *fp, struct seq *seq)
  333. {
  334.   if (seq->count == seq->alloc)
  335.     {
  336.       seq->alloc *= 2;
  337.       seq->lines = (struct line *)
  338.     xrealloc ((char *) seq->lines, seq->alloc * sizeof (struct line));
  339.     }
  340.  
  341.   if (get_line (fp, &seq->lines[seq->count]))
  342.     {
  343.       ++seq->count;
  344.       return 1;
  345.     }
  346.   return 0;
  347. }
  348.  
  349. static void
  350. delseq (struct seq *seq)
  351. {
  352.   int i;
  353.   for (i = 0; i < seq->count; i++)
  354.     if (seq->lines[i].beg)
  355.       freeline (&seq->lines[i]);
  356.   free ((char *) seq->lines);
  357. }
  358.  
  359. /* Return <0 if the join field in LINE1 compares less than the one in LINE2;
  360.    >0 if it compares greater; 0 if it compares equal.  */
  361.  
  362. static int
  363. keycmp (struct line *line1, struct line *line2)
  364. {
  365.   const char *beg1, *beg2;    /* Start of field to compare in each file.  */
  366.   int len1, len2;        /* Length of fields to compare.  */
  367.   int diff;
  368.  
  369.   if (join_field_1 < line1->nfields)
  370.     {
  371.       beg1 = line1->fields[join_field_1].beg;
  372.       len1 = line1->fields[join_field_1].len;
  373.     }
  374.   else
  375.     {
  376.       beg1 = NULL;
  377.       len1 = 0;
  378.     }
  379.  
  380.   if (join_field_2 < line2->nfields)
  381.     {
  382.       beg2 = line2->fields[join_field_2].beg;
  383.       len2 = line2->fields[join_field_2].len;
  384.     }
  385.   else
  386.     {
  387.       beg2 = NULL;
  388.       len2 = 0;
  389.     }
  390.  
  391.   if (len1 == 0)
  392.     return len2 == 0 ? 0 : -1;
  393.   if (len2 == 0)
  394.     return 1;
  395.  
  396.   /* Use an if-statement here rather than a function variable to
  397.      avoid portability hassles of getting a non-conflicting declaration
  398.      of memcmp.  */
  399.   if (ignore_case)
  400.     diff = memcasecmp (beg1, beg2, min (len1, len2));
  401.   else
  402.     diff = memcmp (beg1, beg2, min (len1, len2));
  403.  
  404.   if (diff)
  405.     return diff;
  406.   return len1 - len2;
  407. }
  408.  
  409. /* Print field N of LINE if it exists and is nonempty, otherwise
  410.    `empty_filler' if it is nonempty.  */
  411.  
  412. static void
  413. prfield (int n, struct line *line)
  414. {
  415.   int len;
  416.  
  417.   if (n < line->nfields)
  418.     {
  419.       len = line->fields[n].len;
  420.       if (len)
  421.     fwrite (line->fields[n].beg, 1, len, stdout);
  422.       else if (empty_filler)
  423.     fputs (empty_filler, stdout);
  424.     }
  425.   else if (empty_filler)
  426.     fputs (empty_filler, stdout);
  427. }
  428.  
  429. /* Print the join of LINE1 and LINE2.  */
  430.  
  431. static void
  432. prjoin (struct line *line1, struct line *line2)
  433. {
  434.   const struct outlist *outlist;
  435.  
  436.   outlist = outlist_head.next;
  437.   if (outlist)
  438.     {
  439.       const struct outlist *o;
  440.  
  441.       o = outlist;
  442.       while (1)
  443.     {
  444.       int field;
  445.       struct line *line;
  446.  
  447.       if (o->file == 0)
  448.         {
  449.           if (line1 == &uni_blank)
  450.             {
  451.           line = line2;
  452.           field = join_field_2;
  453.         }
  454.           else
  455.             {
  456.           line = line1;
  457.           field = join_field_1;
  458.         }
  459.         }
  460.       else
  461.         {
  462.           line = (o->file == 1 ? line1 : line2);
  463.           assert (o->field >= 0);
  464.           field = o->field;
  465.         }
  466.       prfield (field, line);
  467.       o = o->next;
  468.       if (o == NULL)
  469.         break;
  470.       putchar (tab ? tab : ' ');
  471.     }
  472.       putchar ('\n');
  473.     }
  474.   else
  475.     {
  476.       int i;
  477.  
  478.       if (line1 == &uni_blank)
  479.     {
  480.       struct line *t;
  481.       t = line1;
  482.       line1 = line2;
  483.       line2 = t;
  484.     }
  485.       prfield (join_field_1, line1);
  486.       for (i = 0; i < join_field_1 && i < line1->nfields; ++i)
  487.     {
  488.       putchar (tab ? tab : ' ');
  489.       prfield (i, line1);
  490.     }
  491.       for (i = join_field_1 + 1; i < line1->nfields; ++i)
  492.     {
  493.       putchar (tab ? tab : ' ');
  494.       prfield (i, line1);
  495.     }
  496.  
  497.       for (i = 0; i < join_field_2 && i < line2->nfields; ++i)
  498.     {
  499.       putchar (tab ? tab : ' ');
  500.       prfield (i, line2);
  501.     }
  502.       for (i = join_field_2 + 1; i < line2->nfields; ++i)
  503.     {
  504.       putchar (tab ? tab : ' ');
  505.       prfield (i, line2);
  506.     }
  507.       putchar ('\n');
  508.     }
  509. }
  510.  
  511. /* Print the join of the files in FP1 and FP2.  */
  512.  
  513. static void
  514. join (FILE *fp1, FILE *fp2)
  515. {
  516.   struct seq seq1, seq2;
  517.   struct line line;
  518.   int diff, i, j, eof1, eof2;
  519.  
  520.   /* Read the first line of each file.  */
  521.   initseq (&seq1);
  522.   getseq (fp1, &seq1);
  523.   initseq (&seq2);
  524.   getseq (fp2, &seq2);
  525.  
  526.   while (seq1.count && seq2.count)
  527.     {
  528.       diff = keycmp (&seq1.lines[0], &seq2.lines[0]);
  529.       if (diff < 0)
  530.     {
  531.       if (print_unpairables_1)
  532.         prjoin (&seq1.lines[0], &uni_blank);
  533.       freeline (&seq1.lines[0]);
  534.       seq1.count = 0;
  535.       getseq (fp1, &seq1);
  536.       continue;
  537.     }
  538.       if (diff > 0)
  539.     {
  540.       if (print_unpairables_2)
  541.         prjoin (&uni_blank, &seq2.lines[0]);
  542.       freeline (&seq2.lines[0]);
  543.       seq2.count = 0;
  544.       getseq (fp2, &seq2);
  545.       continue;
  546.     }
  547.  
  548.       /* Keep reading lines from file1 as long as they continue to
  549.          match the current line from file2.  */
  550.       eof1 = 0;
  551.       do
  552.     if (!getseq (fp1, &seq1))
  553.       {
  554.         eof1 = 1;
  555.         ++seq1.count;
  556.         break;
  557.       }
  558.       while (!keycmp (&seq1.lines[seq1.count - 1], &seq2.lines[0]));
  559.  
  560.       /* Keep reading lines from file2 as long as they continue to
  561.          match the current line from file1.  */
  562.       eof2 = 0;
  563.       do
  564.     if (!getseq (fp2, &seq2))
  565.       {
  566.         eof2 = 1;
  567.         ++seq2.count;
  568.         break;
  569.       }
  570.       while (!keycmp (&seq1.lines[0], &seq2.lines[seq2.count - 1]));
  571.  
  572.       if (print_pairables)
  573.     {
  574.       for (i = 0; i < seq1.count - 1; ++i)
  575.         for (j = 0; j < seq2.count - 1; ++j)
  576.           prjoin (&seq1.lines[i], &seq2.lines[j]);
  577.     }
  578.  
  579.       for (i = 0; i < seq1.count - 1; ++i)
  580.     freeline (&seq1.lines[i]);
  581.       if (!eof1)
  582.     {
  583.       seq1.lines[0] = seq1.lines[seq1.count - 1];
  584.       seq1.count = 1;
  585.     }
  586.       else
  587.     seq1.count = 0;
  588.  
  589.       for (i = 0; i < seq2.count - 1; ++i)
  590.     freeline (&seq2.lines[i]);
  591.       if (!eof2)
  592.     {
  593.       seq2.lines[0] = seq2.lines[seq2.count - 1];
  594.       seq2.count = 1;
  595.     }
  596.       else
  597.     seq2.count = 0;
  598.     }
  599.  
  600.   if (print_unpairables_1 && seq1.count)
  601.     {
  602.       prjoin (&seq1.lines[0], &uni_blank);
  603.       freeline (&seq1.lines[0]);
  604.       while (get_line (fp1, &line))
  605.     {
  606.       prjoin (&line, &uni_blank);
  607.       freeline (&line);
  608.     }
  609.     }
  610.  
  611.   if (print_unpairables_2 && seq2.count)
  612.     {
  613.       prjoin (&uni_blank, &seq2.lines[0]);
  614.       freeline (&seq2.lines[0]);
  615.       while (get_line (fp2, &line))
  616.     {
  617.       prjoin (&uni_blank, &line);
  618.       freeline (&line);
  619.     }
  620.     }
  621.  
  622.   delseq (&seq1);
  623.   delseq (&seq2);
  624. }
  625.  
  626. /* Add a field spec for field FIELD of file FILE to `outlist'.  */
  627.  
  628. static void
  629. add_field (int file, int field)
  630. {
  631.   struct outlist *o;
  632.  
  633.   assert (file == 0 || file == 1 || file == 2);
  634.   assert (file == 0 ? field < 0 : field >= 0);
  635.  
  636.   o = (struct outlist *) xmalloc (sizeof (struct outlist));
  637.   o->file = file;
  638.   o->field = field;
  639.   o->next = NULL;
  640.  
  641.   /* Add to the end of the list so the fields are in the right order.  */
  642.   outlist_end->next = o;
  643.   outlist_end = o;
  644. }
  645.  
  646. /* Convert a single field specifier string, S, to a *FILE_INDEX, *FIELD_INDEX
  647.    pair.  In S, the field index string is 1-based; *FIELD_INDEX is zero-based.
  648.    If S is valid, return zero.  Otherwise, give a diagnostic, don't update
  649.    *FILE_INDEX or *FIELD_INDEX, and return nonzero.  */
  650.  
  651. static int
  652. decode_field_spec (const char *s, int *file_index, int *field_index)
  653. {
  654.   int invalid = 1;
  655.  
  656.   /* The first character must be 0, 1, or 2.  */
  657.   switch (s[0])
  658.     {
  659.     case '0':
  660.       if (s[1] == '\0')
  661.     {
  662.       *file_index = 0;
  663.       /* Give *field_index an invalid value.  */
  664.       *field_index = -1;
  665.       invalid = 0;
  666.     }
  667.       else
  668.         {
  669.       /* `0' must be all alone -- no `.FIELD'.  */
  670.       error (0, 0, _("invalid field specifier: `%s'"), s);
  671.     }
  672.       break;
  673.  
  674.     case '1':
  675.     case '2':
  676.       if (s[1] == '.' && s[2] != '\0')
  677.         {
  678.       strtol_error s_err;
  679.       long int tmp_long;
  680.  
  681.       s_err = xstrtol (s + 2, NULL, 10, &tmp_long, "");
  682.       if (s_err != LONGINT_OK || tmp_long <= 0 || tmp_long > INT_MAX)
  683.         {
  684.           error (0, 0, _("invalid field number: `%s'"), s + 2);
  685.         }
  686.       else
  687.         {
  688.           *file_index = s[0] - '0';
  689.           /* Convert to a zero-based index.  */
  690.           *field_index = (int) tmp_long - 1;
  691.           invalid = 0;
  692.         }
  693.     }
  694.       break;
  695.  
  696.     default:
  697.       error (0, 0, _("invalid file number in field spec: `%s'"), s);
  698.       break;
  699.     }
  700.   return invalid;
  701. }
  702.  
  703. /* Add the comma or blank separated field spec(s) in STR to `outlist'.
  704.    Return nonzero to indicate failure.  */
  705.  
  706. static int
  707. add_field_list (const char *c_str)
  708. {
  709.   char *p, *str;
  710.  
  711.   /* Make a writable copy of c_str.  */
  712.   str = (char *) alloca (strlen (c_str) + 1);
  713.   strcpy (str, c_str);
  714.  
  715.   p = str;
  716.   do
  717.     {
  718.       int invalid;
  719.       int file_index, field_index;
  720.       char *spec_item = p;
  721.  
  722.       p = strpbrk (p, ", \t");
  723.       if (p)
  724.         *p++ = 0;
  725.       invalid = decode_field_spec (spec_item, &file_index, &field_index);
  726.       if (invalid)
  727.     return 1;
  728.       add_field (file_index, field_index);
  729.       uni_blank.nfields = max (uni_blank.nfields, field_index);
  730.     }
  731.   while (p);
  732.   return 0;
  733. }
  734.  
  735. /* Create a blank line with COUNT fields separated by tabs.  */
  736.  
  737. void
  738. make_blank (struct line *blank, int count)
  739. {
  740.   int i;
  741.   blank->nfields = count;
  742.   blank->beg = xmalloc (blank->nfields + 1);
  743.   blank->fields = (struct field *) xmalloc (sizeof (struct field) * count);
  744.   for (i = 0; i < blank->nfields; i++)
  745.     {
  746.       blank->beg[i] = '\t';
  747.       blank->fields[i].beg = &blank->beg[i];
  748.       blank->fields[i].len = 0;
  749.     }
  750.   blank->beg[i] = '\0';
  751.   blank->lim = &blank->beg[i];
  752. }
  753.  
  754. int
  755. main (int argc, char **argv)
  756. {
  757.   char *names[2];
  758.   FILE *fp1, *fp2;
  759.   int optc, prev_optc = 0, nfiles;
  760.  
  761. #ifdef __EMX__
  762. _wildcard(&argc, &argv);
  763. #endif
  764.  
  765.  
  766.   program_name = argv[0];
  767. #ifndef __EMX__
  768.   setlocale (LC_ALL, "");
  769.   bindtextdomain (PACKAGE, LOCALEDIR);
  770.   textdomain (PACKAGE);
  771. #endif
  772.   /* Initialize this before parsing options.  In parsing options,
  773.      it may be increased.  */
  774.   uni_blank.nfields = 1;
  775.  
  776.   parse_long_options (argc, argv, "join", GNU_PACKAGE, VERSION, usage);
  777.  
  778.   nfiles = 0;
  779.   print_pairables = 1;
  780.  
  781.   while ((optc = getopt_long_only (argc, argv, "-a:e:i1:2:o:t:v:", longopts,
  782.                    (int *) 0)) != EOF)
  783.     {
  784.       long int val;
  785.  
  786.       switch (optc)
  787.     {
  788.     case 0:
  789.       break;
  790.  
  791.     case 'v':
  792.         print_pairables = 0;
  793.         /* Fall through.  */
  794.  
  795.     case 'a':
  796.       if (xstrtol (optarg, NULL, 10, &val, "") != LONGINT_OK
  797.           || (val != 1 && val != 2))
  798.         error (EXIT_FAILURE, 0, _("invalid field number: `%s'"), optarg);
  799.       if (val == 1)
  800.         print_unpairables_1 = 1;
  801.       else
  802.         print_unpairables_2 = 1;
  803.       break;
  804.  
  805.     case 'e':
  806.       empty_filler = optarg;
  807.       break;
  808.  
  809.     case 'i':
  810.       ignore_case = 1;
  811.       break;
  812.  
  813.     case '1':
  814.       if (xstrtol (optarg, NULL, 10, &val, "") != LONGINT_OK
  815.           || val <= 0 || val > INT_MAX)
  816.         {
  817.           error (EXIT_FAILURE, 0,
  818.              _("invalid field number for file 1: `%s'"), optarg);
  819.         }
  820.       join_field_1 = (int) val - 1;
  821.       break;
  822.  
  823.     case '2':
  824.       if (xstrtol (optarg, NULL, 10, &val, "") != LONGINT_OK
  825.           || val <= 0 || val > INT_MAX)
  826.         error (EXIT_FAILURE, 0,
  827.            _("invalid field number for file 2: `%s'"), optarg);
  828.       join_field_2 = (int) val - 1;
  829.       break;
  830.  
  831.     case 'j':
  832.       if (xstrtol (optarg, NULL, 10, &val, "") != LONGINT_OK
  833.           || val <= 0 || val > INT_MAX)
  834.         error (EXIT_FAILURE, 0, _("invalid field number: `%s'"), optarg);
  835.       join_field_1 = join_field_2 = (int) val - 1;
  836.       break;
  837.  
  838.     case 'o':
  839.       if (add_field_list (optarg))
  840.         exit (EXIT_FAILURE);
  841.       break;
  842.  
  843.     case 't':
  844.       tab = *optarg;
  845.       break;
  846.  
  847.     case 1:        /* Non-option argument.  */
  848.       if (prev_optc == 'o' && optind <= argc - 2)
  849.         {
  850.           if (add_field_list (optarg))
  851.         exit (EXIT_FAILURE);
  852.  
  853.           /* Might be continuation of args to -o.  */
  854.           continue;        /* Don't change `prev_optc'.  */
  855.         }
  856.  
  857.       if (nfiles > 1)
  858.         {
  859.           error (0, 0, _("too many non-option arguments"));
  860.           usage (1);
  861.         }
  862.       names[nfiles++] = optarg;
  863.       break;
  864.  
  865.     case '?':
  866.       usage (1);
  867.     }
  868.       prev_optc = optc;
  869.     }
  870.  
  871.   /* Now that we've seen the options, we can construct the blank line
  872.      structure.  */
  873.   make_blank (&uni_blank, uni_blank.nfields);
  874.  
  875.   if (nfiles != 2)
  876.     {
  877.       error (0, 0, _("too few non-option arguments"));
  878.       usage (1);
  879.     }
  880.  
  881.   fp1 = strcmp (names[0], "-") ? fopen (names[0], "r") : stdin;
  882.   if (!fp1)
  883.     error (EXIT_FAILURE, errno, "%s", names[0]);
  884.   fp2 = strcmp (names[1], "-") ? fopen (names[1], "r") : stdin;
  885.   if (!fp2)
  886.     error (EXIT_FAILURE, errno, "%s", names[1]);
  887.   if (fp1 == fp2)
  888.     error (EXIT_FAILURE, errno, _("both files cannot be standard input"));
  889.   join (fp1, fp2);
  890.  
  891.   if (fp1 != stdin && fclose (fp1) == EOF)
  892.     error (EXIT_FAILURE, errno, "%s", names[0]);
  893.   if (fp2 != stdin && fclose (fp2) == EOF)
  894.     error (EXIT_FAILURE, errno, "%s", names[1]);
  895.   if ((fp1 == stdin || fp2 == stdin) && fclose (stdin) == EOF)
  896.     error (EXIT_FAILURE, errno, "-");
  897.   if (ferror (stdout) || fclose (stdout) == EOF)
  898.     error (EXIT_FAILURE, errno, _("write error"));
  899.  
  900.   exit (EXIT_SUCCESS);
  901. }
  902.