home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / textutils-1.19-src.tgz / tar.out / fsf / textutils / src / join.c < prev    next >
C/C++ Source or Header  |  1996-09-28  |  21KB  |  893 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
  16.    Foundation, 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.   -1 FIELD         join on this FIELD of file 1\n\
  187.   -2 FIELD         join on this FIELD of file 2\n\
  188.   -o FORMAT        obey FORMAT while constructing output line\n\
  189.   -t CHAR          use CHAR as input and output field separator\n\
  190.   -v SIDE          like -a SIDE, but suppress joined output lines\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.     }
  202.   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
  203. }
  204.  
  205. static void
  206. ADD_FIELD (struct line *line, const char *field, size_t len)
  207. {
  208.   if (line->nfields >= line->nfields_allocated)
  209.     {
  210.       line->nfields_allocated = (3 * line->nfields_allocated) / 2 + 1;
  211.       line->fields = (struct field *) xrealloc ((char *) line->fields,
  212.                         (line->nfields_allocated
  213.                          * sizeof (struct field)));
  214.     }
  215.   line->fields[line->nfields].beg = field;
  216.   line->fields[line->nfields].len = len;
  217.   ++(line->nfields);
  218. }
  219.  
  220. /* Fill in the `fields' structure in LINE.  */
  221.  
  222. static void
  223. xfields (struct line *line)
  224. {
  225.   int i;
  226.   register char *ptr, *lim;
  227.  
  228.   ptr = line->beg;
  229.   lim = line->lim;
  230.  
  231.   if (!tab)
  232.     {
  233.       /* Skip leading blanks before the first field.  */
  234.       while (ptr < lim && ISSPACE (*ptr))
  235.     ++ptr;
  236.     }
  237.  
  238.   for (i = 0; ptr < lim; ++i)
  239.     {
  240.       if (tab)
  241.     {
  242.       char *beg;
  243.  
  244.       beg = ptr;
  245.       while (ptr < lim && *ptr != tab)
  246.         ++ptr;
  247.       ADD_FIELD (line, beg, ptr - beg);
  248.       if (ptr < lim)
  249.         ++ptr;
  250.     }
  251.       else
  252.     {
  253.       char *beg;
  254.  
  255.       beg = ptr;
  256.       while (ptr < lim && !ISSPACE (*ptr))
  257.         ++ptr;
  258.       ADD_FIELD (line, beg, ptr - beg);
  259.       while (ptr < lim && ISSPACE (*ptr))
  260.         ++ptr;
  261.     }
  262.     }
  263.  
  264.   if (ptr > line->beg && ((tab && ISSPACE (ptr[-1])) || ptr[-1] == tab))
  265.     {
  266.       /* Add one more (empty) field because the last character of the
  267.      line was a delimiter.  */
  268.       ADD_FIELD (line, NULL, 0);
  269.     }
  270. }
  271.  
  272. /* Read a line from FP into LINE and split it into fields.
  273.    Return 0 if EOF, 1 otherwise.  */
  274.  
  275. static int
  276. get_line (FILE *fp, struct line *line)
  277. {
  278.   static int linesize = 80;
  279.   int c, i;
  280.   char *ptr;
  281.  
  282.   if (feof (fp))
  283.     return 0;
  284.  
  285.   ptr = xmalloc (linesize);
  286.  
  287.   for (i = 0; (c = getc (fp)) != EOF && c != '\n'; ++i)
  288.     {
  289.       if (i == linesize)
  290.     {
  291.       linesize *= 2;
  292.       ptr = xrealloc (ptr, linesize);
  293.     }
  294.       ptr[i] = c;
  295.     }
  296.  
  297.   if (c == EOF && i == 0)
  298.     {
  299.       free (ptr);
  300.       return 0;
  301.     }
  302.  
  303.   line->beg = ptr;
  304.   line->lim = line->beg + i;
  305.   line->nfields_allocated = 0;
  306.   line->nfields = 0;
  307.   line->fields = NULL;
  308.   xfields (line);
  309.   return 1;
  310. }
  311.  
  312. static void
  313. freeline (struct line *line)
  314. {
  315.   free ((char *) line->fields);
  316.   free (line->beg);
  317.   line->beg = NULL;
  318. }
  319.  
  320. static void
  321. initseq (struct seq *seq)
  322. {
  323.   seq->count = 0;
  324.   seq->alloc = 1;
  325.   seq->lines = (struct line *) xmalloc (seq->alloc * sizeof (struct line));
  326. }
  327.  
  328. /* Read a line from FP and add it to SEQ.  Return 0 if EOF, 1 otherwise.  */
  329.  
  330. static int
  331. getseq (FILE *fp, struct seq *seq)
  332. {
  333.   if (seq->count == seq->alloc)
  334.     {
  335.       seq->alloc *= 2;
  336.       seq->lines = (struct line *)
  337.     xrealloc ((char *) seq->lines, seq->alloc * sizeof (struct line));
  338.     }
  339.  
  340.   if (get_line (fp, &seq->lines[seq->count]))
  341.     {
  342.       ++seq->count;
  343.       return 1;
  344.     }
  345.   return 0;
  346. }
  347.  
  348. static void
  349. delseq (struct seq *seq)
  350. {
  351.   int i;
  352.   for (i = 0; i < seq->count; i++)
  353.     if (seq->lines[i].beg)
  354.       freeline (&seq->lines[i]);
  355.   free ((char *) seq->lines);
  356. }
  357.  
  358. /* Return <0 if the join field in LINE1 compares less than the one in LINE2;
  359.    >0 if it compares greater; 0 if it compares equal.  */
  360.  
  361. static int
  362. keycmp (struct line *line1, struct line *line2)
  363. {
  364.   const char *beg1, *beg2;    /* Start of field to compare in each file.  */
  365.   int len1, len2;        /* Length of fields to compare.  */
  366.   int diff;
  367.  
  368.   if (join_field_1 < line1->nfields)
  369.     {
  370.       beg1 = line1->fields[join_field_1].beg;
  371.       len1 = line1->fields[join_field_1].len;
  372.     }
  373.   else
  374.     {
  375.       beg1 = NULL;
  376.       len1 = 0;
  377.     }
  378.  
  379.   if (join_field_2 < line2->nfields)
  380.     {
  381.       beg2 = line2->fields[join_field_2].beg;
  382.       len2 = line2->fields[join_field_2].len;
  383.     }
  384.   else
  385.     {
  386.       beg2 = NULL;
  387.       len2 = 0;
  388.     }
  389.  
  390.   if (len1 == 0)
  391.     return len2 == 0 ? 0 : -1;
  392.   if (len2 == 0)
  393.     return 1;
  394.  
  395.   /* Use an if-statement here rather than a function variable to
  396.      avoid portability hassles of getting a non-conflicting declaration
  397.      of memcmp.  */
  398.   if (ignore_case)
  399.     diff = memcasecmp (beg1, beg2, min (len1, len2));
  400.   else
  401.     diff = memcmp (beg1, beg2, min (len1, len2));
  402.  
  403.   if (diff)
  404.     return diff;
  405.   return len1 - len2;
  406. }
  407.  
  408. /* Print field N of LINE if it exists and is nonempty, otherwise
  409.    `empty_filler' if it is nonempty.  */
  410.  
  411. static void
  412. prfield (int n, struct line *line)
  413. {
  414.   int len;
  415.  
  416.   if (n < line->nfields)
  417.     {
  418.       len = line->fields[n].len;
  419.       if (len)
  420.     fwrite (line->fields[n].beg, 1, len, stdout);
  421.       else if (empty_filler)
  422.     fputs (empty_filler, stdout);
  423.     }
  424.   else if (empty_filler)
  425.     fputs (empty_filler, stdout);
  426. }
  427.  
  428. /* Print the join of LINE1 and LINE2.  */
  429.  
  430. static void
  431. prjoin (struct line *line1, struct line *line2)
  432. {
  433.   const struct outlist *outlist;
  434.  
  435.   outlist = outlist_head.next;
  436.   if (outlist)
  437.     {
  438.       const struct outlist *o;
  439.  
  440.       o = outlist;
  441.       while (1)
  442.     {
  443.       int field;
  444.       struct line *line;
  445.  
  446.       if (o->file == 0)
  447.         {
  448.           if (line1 == &uni_blank)
  449.             {
  450.           line = line2;
  451.           field = join_field_2;
  452.         }
  453.           else
  454.             {
  455.           line = line1;
  456.           field = join_field_1;
  457.         }
  458.         }
  459.       else
  460.         {
  461.           line = (o->file == 1 ? line1 : line2);
  462.           field = o->field;
  463.         }
  464.       prfield (field, line);
  465.       o = o->next;
  466.       if (o == NULL)
  467.         break;
  468.       putchar (tab ? tab : ' ');
  469.     }
  470.       putchar ('\n');
  471.     }
  472.   else
  473.     {
  474.       int i;
  475.  
  476.       if (line1 == &uni_blank)
  477.     {
  478.       struct line *t;
  479.       t = line1;
  480.       line1 = line2;
  481.       line2 = t;
  482.     }
  483.       prfield (join_field_1, line1);
  484.       for (i = 0; i < join_field_1 && i < line1->nfields; ++i)
  485.     {
  486.       putchar (tab ? tab : ' ');
  487.       prfield (i, line1);
  488.     }
  489.       for (i = join_field_1 + 1; i < line1->nfields; ++i)
  490.     {
  491.       putchar (tab ? tab : ' ');
  492.       prfield (i, line1);
  493.     }
  494.  
  495.       for (i = 0; i < join_field_2 && i < line2->nfields; ++i)
  496.     {
  497.       putchar (tab ? tab : ' ');
  498.       prfield (i, line2);
  499.     }
  500.       for (i = join_field_2 + 1; i < line2->nfields; ++i)
  501.     {
  502.       putchar (tab ? tab : ' ');
  503.       prfield (i, line2);
  504.     }
  505.       putchar ('\n');
  506.     }
  507. }
  508.  
  509. /* Print the join of the files in FP1 and FP2.  */
  510.  
  511. static void
  512. join (FILE *fp1, FILE *fp2)
  513. {
  514.   struct seq seq1, seq2;
  515.   struct line line;
  516.   int diff, i, j, eof1, eof2;
  517.  
  518.   /* Read the first line of each file.  */
  519.   initseq (&seq1);
  520.   getseq (fp1, &seq1);
  521.   initseq (&seq2);
  522.   getseq (fp2, &seq2);
  523.  
  524.   while (seq1.count && seq2.count)
  525.     {
  526.       diff = keycmp (&seq1.lines[0], &seq2.lines[0]);
  527.       if (diff < 0)
  528.     {
  529.       if (print_unpairables_1)
  530.         prjoin (&seq1.lines[0], &uni_blank);
  531.       freeline (&seq1.lines[0]);
  532.       seq1.count = 0;
  533.       getseq (fp1, &seq1);
  534.       continue;
  535.     }
  536.       if (diff > 0)
  537.     {
  538.       if (print_unpairables_2)
  539.         prjoin (&uni_blank, &seq2.lines[0]);
  540.       freeline (&seq2.lines[0]);
  541.       seq2.count = 0;
  542.       getseq (fp2, &seq2);
  543.       continue;
  544.     }
  545.  
  546.       /* Keep reading lines from file1 as long as they continue to
  547.          match the current line from file2.  */
  548.       eof1 = 0;
  549.       do
  550.     if (!getseq (fp1, &seq1))
  551.       {
  552.         eof1 = 1;
  553.         ++seq1.count;
  554.         break;
  555.       }
  556.       while (!keycmp (&seq1.lines[seq1.count - 1], &seq2.lines[0]));
  557.  
  558.       /* Keep reading lines from file2 as long as they continue to
  559.          match the current line from file1.  */
  560.       eof2 = 0;
  561.       do
  562.     if (!getseq (fp2, &seq2))
  563.       {
  564.         eof2 = 1;
  565.         ++seq2.count;
  566.         break;
  567.       }
  568.       while (!keycmp (&seq1.lines[0], &seq2.lines[seq2.count - 1]));
  569.  
  570.       if (print_pairables)
  571.     {
  572.       for (i = 0; i < seq1.count - 1; ++i)
  573.         for (j = 0; j < seq2.count - 1; ++j)
  574.           prjoin (&seq1.lines[i], &seq2.lines[j]);
  575.     }
  576.  
  577.       for (i = 0; i < seq1.count - 1; ++i)
  578.     freeline (&seq1.lines[i]);
  579.       if (!eof1)
  580.     {
  581.       seq1.lines[0] = seq1.lines[seq1.count - 1];
  582.       seq1.count = 1;
  583.     }
  584.       else
  585.     seq1.count = 0;
  586.  
  587.       for (i = 0; i < seq2.count - 1; ++i)
  588.     freeline (&seq2.lines[i]);
  589.       if (!eof2)
  590.     {
  591.       seq2.lines[0] = seq2.lines[seq2.count - 1];
  592.       seq2.count = 1;
  593.     }
  594.       else
  595.     seq2.count = 0;
  596.     }
  597.  
  598.   if (print_unpairables_1 && seq1.count)
  599.     {
  600.       prjoin (&seq1.lines[0], &uni_blank);
  601.       freeline (&seq1.lines[0]);
  602.       while (get_line (fp1, &line))
  603.     {
  604.       prjoin (&line, &uni_blank);
  605.       freeline (&line);
  606.     }
  607.     }
  608.  
  609.   if (print_unpairables_2 && seq2.count)
  610.     {
  611.       prjoin (&uni_blank, &seq2.lines[0]);
  612.       freeline (&seq2.lines[0]);
  613.       while (get_line (fp2, &line))
  614.     {
  615.       prjoin (&uni_blank, &line);
  616.       freeline (&line);
  617.     }
  618.     }
  619.  
  620.   delseq (&seq1);
  621.   delseq (&seq2);
  622. }
  623.  
  624. /* Add a field spec for field FIELD of file FILE to `outlist'.  */
  625.  
  626. static void
  627. add_field (int file, int field)
  628. {
  629.   struct outlist *o;
  630.  
  631.   assert (file == 0 || file == 1 || file == 2);
  632.   assert (field >= 0);
  633.  
  634.   o = (struct outlist *) xmalloc (sizeof (struct outlist));
  635.   o->file = file;
  636.   o->field = field;
  637.   o->next = NULL;
  638.  
  639.   /* Add to the end of the list so the fields are in the right order.  */
  640.   outlist_end->next = o;
  641.   outlist_end = o;
  642. }
  643.  
  644. /* Convert a single field specifier string, S, to a *FILE_INDEX, *FIELD_INDEX
  645.    pair.  In S, the field index string is 1-based; *FIELD_INDEX is zero-based.
  646.    If S is valid, return zero.  Otherwise, give a diagnostic, don't update
  647.    *FILE_INDEX or *FIELD_INDEX, and return nonzero.  */
  648.  
  649. static int
  650. decode_field_spec (const char *s, int *file_index, int *field_index)
  651. {
  652.   int invalid = 1;
  653.  
  654.   /* The first character must be 0, 1, or 2.  */
  655.   switch (s[0])
  656.     {
  657.     case '0':
  658.       if (s[1] == '\0')
  659.     {
  660.       *file_index = 0;
  661.       /* Leave *field_index undefined.  */
  662.       invalid = 0;
  663.     }
  664.       else
  665.         {
  666.       /* `0' must be all alone -- no `.FIELD'.  */
  667.       error (0, 0, _("invalid field specifier: `%s'"), s);
  668.     }
  669.       break;
  670.  
  671.     case '1':
  672.     case '2':
  673.       if (s[1] == '.' && s[2] != '\0')
  674.         {
  675.       strtol_error s_err;
  676.       long int tmp_long;
  677.  
  678.       s_err = xstrtol (s + 2, NULL, 10, &tmp_long, NULL);
  679.       if (s_err != LONGINT_OK || tmp_long <= 0 || tmp_long > INT_MAX)
  680.         {
  681.           error (0, 0, _("invalid field number: `%s'"), s + 2);
  682.         }
  683.       else
  684.         {
  685.           *file_index = s[0] - '0';
  686.           /* Convert to a zero-based index.  */
  687.           *field_index = (int) tmp_long - 1;
  688.           invalid = 0;
  689.         }
  690.     }
  691.       break;
  692.  
  693.     default:
  694.       error (0, 0, _("invalid file number in field spec: `%s'"), s);
  695.       break;
  696.     }
  697.   return invalid;
  698. }
  699.  
  700. /* Add the comma or blank separated field spec(s) in STR to `outlist'.
  701.    Return nonzero to indicate failure.  */
  702.  
  703. static int
  704. add_field_list (const char *c_str)
  705. {
  706.   char *p, *str;
  707.  
  708.   /* Make a writable copy of c_str.  */
  709.   str = (char *) alloca (strlen (c_str) + 1);
  710.   strcpy (str, c_str);
  711.  
  712.   p = str;
  713.   do
  714.     {
  715.       int invalid;
  716.       int file_index, field_index;
  717.       char *spec_item = p;
  718.  
  719.       p = strpbrk (p, ", \t");
  720.       if (p)
  721.         *p++ = 0;
  722.       invalid = decode_field_spec (spec_item, &file_index, &field_index);
  723.       if (invalid)
  724.     return 1;
  725.       add_field (file_index, field_index);
  726.       uni_blank.nfields = max (uni_blank.nfields, field_index);
  727.     }
  728.   while (p);
  729.   return 0;
  730. }
  731.  
  732. /* Create a blank line with COUNT fields separated by tabs.  */
  733.  
  734. void
  735. make_blank (struct line *blank, int count)
  736. {
  737.   int i;
  738.   blank->nfields = count;
  739.   blank->beg = xmalloc (blank->nfields + 1);
  740.   blank->fields = (struct field *) xmalloc (sizeof (struct field) * count);
  741.   for (i = 0; i < blank->nfields; i++)
  742.     {
  743.       blank->beg[i] = '\t';
  744.       blank->fields[i].beg = &blank->beg[i];
  745.       blank->fields[i].len = 0;
  746.     }
  747.   blank->beg[i] = '\0';
  748.   blank->lim = &blank->beg[i];
  749. }
  750.  
  751. int
  752. main (int argc, char **argv)
  753. {
  754.   char *names[2];
  755.   FILE *fp1, *fp2;
  756.   int optc, prev_optc = 0, nfiles;
  757.  
  758.   program_name = argv[0];
  759.   setlocale (LC_ALL, "");
  760.   bindtextdomain (PACKAGE, LOCALEDIR);
  761.   textdomain (PACKAGE);
  762.  
  763.   /* Initialize this before parsing options.  In parsing options,
  764.      it may be increased.  */
  765.   uni_blank.nfields = 1;
  766.  
  767.   parse_long_options (argc, argv, "join", PACKAGE_VERSION, usage);
  768.  
  769.   nfiles = 0;
  770.   print_pairables = 1;
  771.  
  772.   while ((optc = getopt_long_only (argc, argv, "-a:e:i1:2:o:t:v:", longopts,
  773.                    (int *) 0)) != EOF)
  774.     {
  775.       long int val;
  776.  
  777.       switch (optc)
  778.     {
  779.     case 0:
  780.       break;
  781.  
  782.     case 'v':
  783.         print_pairables = 0;
  784.         /* Fall through.  */
  785.  
  786.     case 'a':
  787.       if (xstrtol (optarg, NULL, 10, &val, NULL) != LONGINT_OK
  788.           || (val != 1 && val != 2))
  789.         error (EXIT_FAILURE, 0, _("invalid field number: `%s'"), optarg);
  790.       if (val == 1)
  791.         print_unpairables_1 = 1;
  792.       else
  793.         print_unpairables_2 = 1;
  794.       break;
  795.  
  796.     case 'e':
  797.       empty_filler = optarg;
  798.       break;
  799.  
  800.     case 'i':
  801.       ignore_case = 1;
  802.       break;
  803.  
  804.     case '1':
  805.       if (xstrtol (optarg, NULL, 10, &val, NULL) != LONGINT_OK
  806.           || val <= 0 || val > INT_MAX)
  807.         {
  808.           error (EXIT_FAILURE, 0,
  809.              _("invalid field number for file 1: `%s'"), optarg);
  810.         }
  811.       join_field_1 = (int) val - 1;
  812.       break;
  813.  
  814.     case '2':
  815.       if (xstrtol (optarg, NULL, 10, &val, NULL) != LONGINT_OK
  816.           || val <= 0 || val > INT_MAX)
  817.         error (EXIT_FAILURE, 0,
  818.            _("invalid field number for file 2: `%s'"), optarg);
  819.       join_field_2 = (int) val - 1;
  820.       break;
  821.  
  822.     case 'j':
  823.       if (xstrtol (optarg, NULL, 10, &val, NULL) != LONGINT_OK
  824.           || val <= 0 || val > INT_MAX)
  825.         error (EXIT_FAILURE, 0, _("invalid field number: `%s'"), optarg);
  826.       join_field_1 = join_field_2 = (int) val - 1;
  827.       break;
  828.  
  829.     case 'o':
  830.       if (add_field_list (optarg))
  831.         exit (EXIT_FAILURE);
  832.       break;
  833.  
  834.     case 't':
  835.       tab = *optarg;
  836.       break;
  837.  
  838.     case 1:        /* Non-option argument.  */
  839.       if (prev_optc == 'o' && optind <= argc - 2)
  840.         {
  841.           if (add_field_list (optarg))
  842.         exit (EXIT_FAILURE);
  843.  
  844.           /* Might be continuation of args to -o.  */
  845.           continue;        /* Don't change `prev_optc'.  */
  846.         }
  847.  
  848.       if (nfiles > 1)
  849.         {
  850.           error (0, 0, _("too many non-option arguments"));
  851.           usage (1);
  852.         }
  853.       names[nfiles++] = optarg;
  854.       break;
  855.  
  856.     case '?':
  857.       usage (1);
  858.     }
  859.       prev_optc = optc;
  860.     }
  861.  
  862.   /* Now that we've seen the options, we can construct the blank line
  863.      structure.  */
  864.   make_blank (&uni_blank, uni_blank.nfields);
  865.  
  866.   if (nfiles != 2)
  867.     {
  868.       error (0, 0, _("too few non-option arguments"));
  869.       usage (1);
  870.     }
  871.  
  872.   fp1 = strcmp (names[0], "-") ? fopen (names[0], "r") : stdin;
  873.   if (!fp1)
  874.     error (EXIT_FAILURE, errno, "%s", names[0]);
  875.   fp2 = strcmp (names[1], "-") ? fopen (names[1], "r") : stdin;
  876.   if (!fp2)
  877.     error (EXIT_FAILURE, errno, "%s", names[1]);
  878.   if (fp1 == fp2)
  879.     error (EXIT_FAILURE, errno, _("both files cannot be standard input"));
  880.   join (fp1, fp2);
  881.  
  882.   if (fp1 != stdin && fclose (fp1) == EOF)
  883.     error (EXIT_FAILURE, errno, "%s", names[0]);
  884.   if (fp2 != stdin && fclose (fp2) == EOF)
  885.     error (EXIT_FAILURE, errno, "%s", names[1]);
  886.   if ((fp1 == stdin || fp2 == stdin) && fclose (stdin) == EOF)
  887.     error (EXIT_FAILURE, errno, "-");
  888.   if (ferror (stdout) || fclose (stdout) == EOF)
  889.     error (EXIT_FAILURE, errno, _("write error"));
  890.  
  891.   exit (EXIT_SUCCESS);
  892. }
  893.