home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / UNIX / GNU / recode-3.4-MIHS / src / recode.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-06  |  76.7 KB  |  2,862 lines

  1. /* Conversion of files between different charsets and usages.
  2.    Copyright (C) 1990, 1992, 1993, 1994 Free Software Foundation, Inc.
  3.    Francois Pinard <pinard@iro.umontreal.ca>, 1990.
  4.  
  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 2, or (at your option)
  8.    any later version.
  9.  
  10.    This program is distributed in the hope that it will be useful, but
  11.    WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13.    General Public License for more details.
  14.  
  15.    You should have received a copy of the GNU General Public License
  16.    along with this program; if not, write to the Free Software
  17.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18. */
  19.  
  20. #include "recode.h"
  21.  
  22. /* Maximum number of single step methods.  */
  23. #define MAX_SINGLE_STEPS 300
  24.  
  25. /* Maximum length of a conversion sequence.  */
  26. #define MAX_SEQUENCE 12
  27.  
  28. /* Global declarations and definitions.  */
  29.  
  30. #include <ctype.h>
  31.  
  32. #include <sys/types.h>
  33. #include <sys/stat.h>
  34.  
  35. #include <setjmp.h>
  36. #include <signal.h>
  37. #ifndef RETSIGTYPE
  38. #define RETSIGTYPE void
  39. #endif
  40.  
  41. #ifdef HAVE_STRING_H
  42. #include <string.h>
  43. #else
  44. #include <strings.h>
  45. #define strchr index
  46. #define strrchr rindex
  47. #endif
  48.  
  49. #ifdef MSDOS
  50. #define MSDOS_or_OS2 1
  51. #include <dir.h>
  52. #define unlink dummy1
  53. #include <io.h>
  54. #undef unlink
  55. #include <fcntl.h>
  56. #endif
  57.  
  58. #ifdef OS2
  59. #define MSDOS_or_OS2 1
  60. #include <io.h>
  61. #include <fcntl.h>
  62. #endif
  63.  
  64. #include <errno.h>
  65. #ifndef errno
  66. extern int errno;
  67. #endif
  68.  
  69. #include "getopt.h"
  70.  
  71. /* tmpnam/tmpname/mktemp/tmpfile and the associate logic has been the
  72.    main portability headache of GNU recode :-(.
  73.    
  74.    People reported that tmpname does not exist everywhere.  On OS/2,
  75.    recode aborts if the prefix has more than five characters.
  76.    
  77.    tmpnam seems to exist everywhere so far.  But NeXT's tmpnam() is such
  78.    that, if called many times in succession, it will always return the
  79.    same value.  One has to really open a file with the returned name
  80.    first, for the next call to tmpnam() to return a different value.  I
  81.    can manage it for a single invocation of recode, but using two recode
  82.    invocations connected with a shell pipe, on the NeXT, creates a race
  83.    by which both copies may call tmpnam() in parallel, then getting the
  84.    same value, and will consequently open the same temporary file.
  85.    
  86.    Noah Friedman <friedman@gnu.ai.mit.edu> suggests opening the file with
  87.    O_EXCL, and when the open presumably fails, call tmpnam again, or try
  88.    the mktemp routine in the GNU C library...maybe that will work better.
  89.    
  90.    Michael I Bushnell <mib@gnu.ai.mit.edu> suggests always using tmpfile,
  91.    which opens the file too, using the O_EXCL option to open.
  92.    
  93.    I'm trying this last suggestion, rewinding instead of closing.
  94.    Someone reported, a long while ago, that rewind did not work on his
  95.    system, so I reverted to opening and closing the temporary files all
  96.    the time.  I lost the precise references for this problem.  In any
  97.    case, I'm reusing rewind with tmpfile, now.  Hopefully, someone will
  98.    tell me if this creates a problem somewhere!  */
  99.  
  100. /* The previous round used tmpnam(3).  This one tries tmpfile(3).  */
  101. /* #define USE_TMPNAM 1 */
  102. #define USE_TMPFILE 1
  103.  
  104. #ifdef USE_TMPNAM
  105. /* Guarantee some value for L_tmpnam.  */
  106. #ifdef MSDOS
  107.  
  108. #define L_tmpnam 13
  109.  
  110. #else /* not MSDOS */
  111.  
  112. char *tmpnam ();
  113.  
  114. #ifndef L_tmpnam
  115. #include "pathmax.h"
  116. #define L_tmpnam PATH_MAX
  117. #endif
  118.  
  119. #endif /* not MSDOS */
  120. #endif /* USE_TMPNAM */
  121.  
  122. #ifdef USE_TMPFILE
  123.  
  124. FILE *tmpfile _((void));
  125.  
  126. #endif /* USE_TMPFILE */
  127.  
  128. #ifdef WITH_DMALLOC
  129. #include <dmalloc.h>
  130. #endif
  131.  
  132. #ifdef MSDOS
  133. /* Increase stack size, so init_recode_rfc1345 works.  */
  134. extern unsigned _stklen = 10000U;
  135. #endif
  136.  
  137. /* Variables.  */
  138.  
  139. const char *const copyright_string = "\
  140. This program is free software; you can redistribute it and/or modify\n\
  141. it under the terms of the GNU General Public License as published by\n\
  142. the Free Software Foundation; either version 2, or (at your option)\n\
  143. any later version.\n\
  144. \n\
  145. This program is distributed in the hope that it will be useful,\n\
  146. but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
  147. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\
  148. GNU General Public License for more details.\n\
  149. \n\
  150. You should have received a copy of the GNU General Public License\n\
  151. along with this program; if not, write to the Free Software\n\
  152. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n";
  153.  
  154. /* The name this program was run with. */
  155. const char *program_path;
  156. const char *program_name;
  157.  
  158. /* If non-zero, display usage information and exit.  */
  159. static int show_help = 0;
  160.  
  161. /* If non-zero, print the version on standard output and exit.  */
  162. static int show_version = 0;
  163.  
  164. /* If non-zero, show a list of one or all known charsets, then exit.  */
  165. static int show_charsets = 0;
  166.  
  167. /* If non-zero, show a restricted list of charsets.  */
  168. static int show_restricted_charsets = 0;
  169.  
  170. /* Indicates the format for showing only one charset.  */
  171. enum list_format list_format = NO_FORMAT;
  172.  
  173. /* If non-zero, merely explore all recoding paths, report and exit.  */
  174. static int auto_check_mode = 0;
  175.  
  176. /* If non-zero, produce C code for initializing the conversion and exit.  */
  177. static int make_header_mode = 0;
  178.  
  179. /* Table name in generated C code.  */
  180. static const char *header_name = NULL;
  181.  
  182. /* If the recoding yields some problems in reversibility in some file,
  183.    this file replacement is denied and it is left unrecoded or, if recode
  184.    is used as a mere filter, the recoding is interrupted.  The following
  185.    option forces the recoding to run to completion and the replacement to
  186.    be done even if the recoding is not reversible.  */
  187. int force_option = 0;
  188.  
  189. /* This option prevents recode from automatically completing charsets.  */
  190. int strict_mapping = 0;
  191.  
  192. /* This option merely inhibits messages about non-reversible recodings, but
  193.    it does not prevent recodings to be aborted or exit status to be set.  */
  194. static int quiet_mode = 0;
  195.  
  196. /* By selecting the following option, the program will echo to stderr the
  197.    sequence of elementary recoding steps which will be taken to effect
  198.    the requested recoding.  */
  199. int verbose_option = 0;
  200.  
  201. /* When a file is recoded over itself, precautions are taken to move the
  202.    timestamps of the original file into the recoded file, so to make the
  203.    recoding the most transparent possible to make, and other tools.
  204.    However, selecting the following option inhibit the timestamps handling,
  205.    thus effectively `touching' the file.  */
  206. int touch_option = 0;
  207.  
  208. /* In `texte' charset, some countries use double quotes to mark diaeresis,
  209.    while other countries prefer colons.  The following variable contains the
  210.    diaeresis character for `texte' charset.  Nominally set to a double
  211.    quote, it can be forced to a colon by an option on recode command.  */
  212. char diaeresis_char = '"';
  213.  
  214. /* For `latex' charset, it is often convenient to recode the diacritics
  215.    only, while letting other LaTeX code using backslashes unrecoded.
  216.    In the other charset, one can edit text as well as LaTeX directives.  */
  217. int diacritics_only = 0;
  218.  
  219. /* For `ibmpc' charset, characters 176 to 223 are use to draw boxes.
  220.    If this variable is set, while getting out of `ibmpc', ASCII
  221.    characters are selected so to approximate these boxes.  */
  222. int ascii_graphics = 0;
  223.  
  224. /* The following charset name will be ignored, if given.  */
  225. static const char *ignored_name = NULL;
  226.  
  227. /* Unabridged names of BEFORE and AFTER charsets, even if still aliases.
  228.    These are used for naming the array in produced C code.  */
  229. static const char *before_full_name;
  230. static const char *after_full_name;
  231.  
  232. /* Ordinals of list, BEFORE and AFTER charset.  */
  233. static CHARSET *list_charset;
  234. static CHARSET *before_charset;
  235. static CHARSET *after_charset;
  236.  
  237. /* Flag telling usage that we are decoding charsets.  */
  238. int decoding_charset_flag = 0;
  239.  
  240. /* Tells how various passes will be interconnected.  */
  241. enum sequence_strategy
  242.   {
  243.     STRATEGY_UNDECIDED,        /* sequencing strategy is undecided yet */
  244.     SEQUENCE_WITH_FILES,    /* do not fork, use intermediate files */
  245.     SEQUENCE_WITH_POPEN,    /* use `popen(3)' to fork processes */
  246.     SEQUENCE_WITH_PIPE        /* fork processes connected with `pipe(2)' */
  247.   };
  248. enum sequence_strategy sequence_strategy = STRATEGY_UNDECIDED;
  249.  
  250. /* Known single steps.  */
  251.  
  252. STEP single_step_array[MAX_SINGLE_STEPS];
  253. int number_of_single_steps;    /* number of announced single steps */
  254.  
  255. const unsigned char *one_to_same; /* identity recoding */
  256.  
  257. CHARSET *rfc1345;        /* special RFC 1345 charset value */
  258.  
  259. /* Array stating the sequence of conversions.  */
  260. const STEP *sequence[MAX_SEQUENCE];
  261. int length_of_sequence;
  262.  
  263. /* Signal handling.  */
  264.  
  265. /*-----------------.
  266. | Signal handler.  |
  267. `-----------------*/
  268.  
  269. static jmp_buf signal_label;    /* where to jump when signal received */
  270. static int interrupted = 0;    /* set when some signal has been received */
  271.  
  272. static RETSIGTYPE
  273. signal_handler (int number)
  274. {
  275.   interrupted = 1;
  276.   signal (number, signal_handler);
  277. }
  278.  
  279. /*------------------------------------------------------------------------.
  280. | Prepare to handle signals, intercept willingful requests for stopping.  |
  281. `------------------------------------------------------------------------*/
  282.  
  283. static void
  284. setup_signals (void)
  285. {
  286.   signal (SIGPIPE, signal_handler);
  287. #if 0
  288.   signal (SIGINT, signal_handler);
  289.   signal (SIGTERM, signal_handler);
  290. #endif
  291. }
  292.  
  293. /* Quality handling.  */
  294.  
  295. /*---------------------------------------.
  296. | Return a string describing a quality.     |
  297. `---------------------------------------*/
  298.  
  299. const char *
  300. quality_to_string (QUALITY quality)
  301. {
  302.   switch (quality)
  303.     {
  304.     default:
  305.       abort ();
  306.  
  307.     case REVERSIBLE:
  308.       return "reversible";
  309.  
  310.     case ONE_TO_ONE:
  311.       return "one to one";
  312.  
  313.     case MANY_TO_ONE:
  314.       return "many to one";
  315.  
  316.     case ONE_TO_MANY:
  317.       return "one to many";
  318.  
  319.     case MANY_TO_MANY:
  320.       return "many to many";
  321.     }
  322. }
  323.  
  324. /*-------------------------------------------------------------------------.
  325. | Return the quality of a step obtained by merging two others steps, given |
  326. | their respective qualities FIRST and SECOND.                   |
  327. `-------------------------------------------------------------------------*/
  328.  
  329. QUALITY 
  330. merge_qualities (QUALITY first, QUALITY second)
  331. {
  332.   switch (first)
  333.     {
  334.     default:
  335.       abort ();
  336.       
  337.     case REVERSIBLE:
  338.       return second;
  339.  
  340.     case ONE_TO_ONE:
  341.       switch (second)
  342.     {
  343.     case REVERSIBLE:
  344.     case ONE_TO_ONE:
  345.       return ONE_TO_ONE;
  346.  
  347.     case MANY_TO_ONE:
  348.     case ONE_TO_MANY:
  349.     case MANY_TO_MANY:
  350.       return second;
  351.     }
  352.  
  353.     case MANY_TO_ONE:
  354.       switch (second)
  355.     {
  356.     case REVERSIBLE:
  357.     case ONE_TO_ONE:
  358.     case MANY_TO_ONE:
  359.       return MANY_TO_ONE;
  360.  
  361.     case ONE_TO_MANY:
  362.     case MANY_TO_MANY:
  363.       return MANY_TO_MANY;
  364.     }
  365.  
  366.     case ONE_TO_MANY:
  367.       switch (second)
  368.     {
  369.     case REVERSIBLE:
  370.     case ONE_TO_ONE:
  371.     case ONE_TO_MANY:
  372.       return ONE_TO_MANY;
  373.  
  374.     case MANY_TO_ONE:
  375.     case MANY_TO_MANY:
  376.       return MANY_TO_MANY;
  377.     }
  378.  
  379.     case MANY_TO_MANY:
  380.       return MANY_TO_MANY;
  381.     }
  382. }
  383.  
  384. /* Charset handling.  */
  385.  
  386. /*----------------------------------------------------.
  387. | Decode the BEFORE:AFTER argument, given in STRING.  |
  388. `----------------------------------------------------*/
  389.  
  390. static void
  391. decode_before_after (const char *string)
  392. {
  393.   char *before;
  394.   char *after;
  395.   char *in;
  396.   char *out;
  397.  
  398.   /* Split the BEFORE:AFTER keyword at the colon.  A backslash can escape
  399.      a colon in both charsets.  */
  400.  
  401.   before = xstrdup (string);
  402.   after = NULL;
  403.   out = before;
  404.  
  405.   for (in = before; *in; in++)
  406.     if (*in == ':' && !after)
  407.       {
  408.     *out++ = '\0';
  409.     after = out;
  410.       }
  411.     else
  412.       {
  413.     if (*in == '\\' && *(in + 1))
  414.       in++;
  415.     *out++ = *in;
  416.       }
  417.   *out = '\0';
  418.  
  419.   if (!after)
  420.     usage (EXIT_FAILURE);
  421.  
  422.   /* Decode both charsets.  */
  423.  
  424.   before_full_name = clean_charset_name (before);
  425.   before_charset = find_charset (before_full_name);
  426.  
  427.   after_full_name = clean_charset_name (after);
  428.   after_charset = find_charset (after_full_name);
  429.  
  430.   /* Free the work area.  */
  431.  
  432.   free (before);
  433. }
  434.  
  435. /* Single step handling.  */
  436.  
  437. /*-------------------------------------------------------------------------.
  438. | Allocate and initialize a new single step, save for the before and after |
  439. | charsets and quality.                               |
  440. `-------------------------------------------------------------------------*/
  441.  
  442. static STEP *
  443. new_single_step (void)
  444. {
  445.   STEP *step;
  446.  
  447.   if (number_of_single_steps == MAX_SINGLE_STEPS)
  448.     error (EXIT_FAILURE, 0, "MAX_SINGLE_STEPS is too small");
  449.  
  450.   step = single_step_array + number_of_single_steps++;
  451.   step->init_recode = NULL;
  452.   step->file_recode = NULL;
  453.   step->one_to_one = NULL;
  454.   step->one_to_many = NULL;
  455.  
  456.   return step;
  457. }
  458.   
  459. /*------------------------------------------------------------------------.
  460. | Create and initialize a new single step for recoding between START_NAME |
  461. | and GOAL_NAME, which are given as strings, give it a recoding QUALITY,  |
  462. | also saving an INIT_RECODE and a FILE_RECODE functions.          |
  463. `------------------------------------------------------------------------*/
  464.  
  465. /* If not __STDC__, do not write prototypes for functionnal parameters,
  466.    because ansi2knr does not clean them.  */
  467.  
  468. #if __STDC__
  469. void
  470. declare_step (const char *before_name, const char *after_name, QUALITY quality,
  471.           void (*init_recode) (STEP *),
  472.           int (*file_recode) (const STEP *, FILE *, FILE *))
  473. #else
  474. void
  475. declare_step (const char *before_name, const char *after_name, QUALITY quality,
  476.           void (*init_recode) (),
  477.           int (*file_recode) ())
  478. #endif
  479. {
  480.   STEP *step;
  481.  
  482.   step = new_single_step ();
  483.   step->before = find_charset (before_name);
  484.   step->after = find_charset (after_name);
  485.   step->quality = quality;
  486.   step->init_recode = init_recode;
  487.   step->file_recode = file_recode;
  488. }
  489.  
  490. /*------------------------------------------------------------------.
  491. | Create a one to one table which is the inverse of the given one.  |
  492. `------------------------------------------------------------------*/
  493.  
  494. unsigned char *
  495. invert_table (const unsigned char *table)
  496. {
  497.   unsigned char flag[256];
  498.   unsigned char *result;
  499.   int table_error;
  500.   int counter;
  501.  
  502.   result = (unsigned char *) xmalloc (256);
  503.   memset (flag, 0, 256);
  504.   table_error = 0;
  505.  
  506.   for (counter = 0; counter < 256; counter++)
  507.     {
  508.       if (flag[table[counter]])
  509.     {
  510.       error (0, 0, "Codes %3d and %3d both recode to %3d",
  511.          result[table[counter]], counter, table[counter]);
  512.       table_error = 1;
  513.     }
  514.       else
  515.     {
  516.       result[table[counter]] = counter;
  517.       flag[table[counter]] = 1;
  518.     }
  519.     }
  520.   if (table_error)
  521.     {
  522.       for (counter = 0; counter < 256; counter++)
  523.     if (!flag[counter])
  524.       error (0, 0, "No character recodes to %3d", counter);
  525.       error (EXIT_FAILURE, 0, "Cannot invert given one-to-one table");
  526.     }
  527.   return result;
  528. }
  529.  
  530. /*-------------------------------------------------------------------------.
  531. | Complete a STEP descriptor by a constructed recoding array for 256 chars |
  532. | and the adequate recoding routine.  If FIRST_HALF_IMPLIED is not zero,   |
  533. | default the unconstrained characters of the first 128 to the identity       |
  534. | mapping.  Use an KNOWN_PAIRS array of NUMBER_OF_PAIRS constraints.  If   |
  535. | REVERSE is not zero, use right_table instead of left_table.           |
  536. `-------------------------------------------------------------------------*/
  537.  
  538. void
  539. complete_pairs (STEP *step, int first_half_implied,
  540.         const KNOWN_PAIR *known_pairs, int number_of_pairs,
  541.         int reverse)
  542. {
  543.   unsigned char left_flag[256];
  544.   unsigned char right_flag[256];
  545.   unsigned char left_table[256];
  546.   unsigned char right_table[256];
  547.   int table_error;
  548.  
  549.   unsigned char *flag;
  550.   unsigned char *table;
  551.   const char **table2;
  552.   char *cursor;
  553.   unsigned char left;
  554.   unsigned char right;
  555.   unsigned char search;
  556.   int counter;
  557.   int used;
  558.  
  559.   /* Init tables with zeroes.  */
  560.  
  561.   memset (left_flag, 0, 256);
  562.   memset (right_flag, 0, 256);
  563.   table_error = 0;
  564.  
  565.   /* Establish known data.  */
  566.  
  567.   for (counter = 0; counter < number_of_pairs; counter++)
  568.     {
  569.       left = known_pairs[counter].left;
  570.       right = known_pairs[counter].right;
  571.  
  572.       /* Set one known correspondance.  */
  573.  
  574.       if (left_flag[left])
  575.     {
  576.       if (!table_error)
  577.         {
  578.           error (0, 0, "Following diagnostics for `%s' to `%s'",
  579.              step->before->name, step->after->name);
  580.           table_error = 1;
  581.         }
  582.       error (0, 0, "Pair no. %d: { %3d, %3d } conflicts with { %3d, %3d }",
  583.          counter, left, right, left, left_table[left]);
  584.     }
  585.       else if (right_flag[right])
  586.     {
  587.       if (!table_error)
  588.         {
  589.           error (0, 0, "Following diagnostics for `%s' to `%s'",
  590.              step->before->name, step->after->name);
  591.           table_error = 1;
  592.         }
  593.       error (0, 0, "Pair no. %d: { %3d, %3d } conflicts with { %3d, %3d }",
  594.          counter, left, right, right_table[right], right);
  595.     }
  596.       else
  597.     {
  598.       left_flag[left] = 1;
  599.       left_table[left] = right;
  600.       right_flag[right] = 1;
  601.       right_table[right] = left;
  602.     }
  603.     }
  604.  
  605.   /* Set all the implied correspondances.  */
  606.  
  607.   if (first_half_implied)
  608.     for (counter = 0; counter < 128; counter++)
  609.       if (!left_flag[counter] && !right_flag[counter])
  610.     {
  611.       left_flag[counter] = 1;
  612.       left_table[counter] = counter;
  613.       right_flag[counter] = 1;
  614.       right_table[counter] = counter;
  615.     }
  616.  
  617.   if (strict_mapping)
  618.     {
  619.  
  620.       /* If the recoding is strict, prepare a one to many table, each
  621.      entry being NULL or a string of a single character.  */
  622.  
  623.       /* Select the proper table.  */
  624.  
  625.       if (reverse)
  626.     {
  627.       flag = right_flag;
  628.       table = right_table;
  629.     }
  630.       else
  631.     {
  632.       flag = left_flag;
  633.       table = left_table;
  634.     }
  635.  
  636.       /* Allocate everything in one blow, so it will be freed likewise.  */
  637.  
  638.       used = 0;
  639.       for (counter = 0; counter < 256; counter++)
  640.     if (flag[counter])
  641.       used++;
  642.  
  643.       table2 = (const char **) xmalloc (256 * sizeof (char *) + 2 * used);
  644.       cursor = (char *) (table2 + 256);
  645.  
  646.       /* Construct the table and the strings in parallel.  */
  647.  
  648.       for (counter = 0; counter < 256; counter++)
  649.     if (flag[counter])
  650.       {
  651.         table2[counter] = cursor;
  652.         *cursor++ = table[counter];
  653.         *cursor++ = '\0';
  654.       }
  655.     else
  656.       table2[counter] = NULL;
  657.  
  658.       /* Save a one to many recoding table.  */
  659.  
  660.       step->file_recode = file_one_to_many;
  661.       step->one_to_many = table2;
  662.     }
  663.   else
  664.     {
  665.  
  666.       /* If the recoding is not strict, compute a reversible one to one
  667.      table.  */
  668.  
  669.       if (table_error)
  670.     error (EXIT_FAILURE, 0,
  671.            "Cannot complete table from set of known pairs");
  672.  
  673.       /* Close the table with small permutation cycles.  */
  674.  
  675.       for (counter = 0; counter < 256; counter++)
  676.     if (!right_flag[counter])
  677.       {
  678.         search = counter;
  679.         while (left_flag[search])
  680.           search = left_table[search];
  681.         left_flag[search] = 1;
  682.         left_table[search] = counter;
  683.         right_flag[counter] = 1;
  684.         right_table[counter] = search;
  685.       }
  686.  
  687.       /* Save a copy of the proper table.  */
  688.  
  689.       step->file_recode = file_one_to_one;
  690.       table = (unsigned char *) xmalloc (256);
  691.       memcpy (table, reverse ? right_table : left_table, 256);
  692.       step->one_to_one = table;
  693.     }
  694. }
  695.  
  696. /*----------------------------------------.
  697. | Initialize all collected single steps.  |
  698. `----------------------------------------*/
  699.  
  700. void
  701. register_all_modules (void)
  702. {
  703.   STEP *step;
  704.   int counter;
  705.   unsigned char *table;
  706.  
  707.   table = (unsigned char *) xmalloc (256);
  708.   for (counter = 0; counter < 256; counter++)
  709.     table[counter] = counter;
  710.   one_to_same = table;
  711.  
  712.   prepare_charset_initialization ();
  713.   number_of_single_steps = 0;
  714.  
  715.   rfc1345 = find_charset ("RFC 1345");
  716.   declare_alias (".", "RFC 1345");
  717.   declare_alias ("ASCII", "ANSI_X3.4-1968");
  718.   declare_alias ("BS", "ASCII-BS");
  719.   declare_alias ("Latin-1", "ISO_8859-1:1987");
  720.  
  721.   /* Needed for compatibility with recode version 3.2.  */
  722.   declare_alias ("lat1", "Latin-1");
  723.  
  724. #include "initstep.h"
  725.  
  726.   for (step = single_step_array;
  727.        step < single_step_array + number_of_single_steps;
  728.        step++)
  729.  
  730.     if (step->file_recode == file_one_to_one
  731.     && step->one_to_one == one_to_same)
  732.  
  733.       step->conversion_cost = 0;
  734.  
  735.     else
  736.       switch (step->quality)
  737.     {
  738.     case REVERSIBLE:
  739.       step->conversion_cost = 2;
  740.       break;
  741.  
  742.     case ONE_TO_ONE:
  743.       step->conversion_cost = 30;
  744.       break;
  745.  
  746.     case MANY_TO_ONE:
  747.       step->conversion_cost = 10;
  748.       break;
  749.  
  750.     case ONE_TO_MANY:
  751.       step->conversion_cost = 40;
  752.       break;
  753.  
  754.     case MANY_TO_MANY:
  755.       step->conversion_cost = 50;
  756.       break;
  757.     }
  758.  
  759.   /* For all RFC 1345 participating steps, halve the cost since they
  760.      come in pair.  */
  761.  
  762.   for (counter = 0; counter < number_of_single_steps; counter++)
  763.     if (single_step_array[counter].before == rfc1345
  764.     || single_step_array[counter].after == rfc1345)
  765.       single_step_array[counter].conversion_cost /= 2;
  766. }
  767.  
  768. /*-------------------------------------------------------------------------.
  769. | Produce a C include file representing the recoding, on standard output.  |
  770. `-------------------------------------------------------------------------*/
  771.  
  772. static void
  773. output_header_file (void)
  774. {
  775.   const STEP *step;        /* step being analysed */
  776.   int column;            /* column counter */
  777.   char *name;            /* constructed name */
  778.   char *cursor;            /* cursor in constructed name */
  779.   const char *cursor2;        /* cursor to study strings */
  780.   int counter;            /* general purpose counter */
  781.  
  782.   /* This function is called only when the recoding sequence contains a
  783.      single step, so it is safe to use sequence[0] for the step.  */
  784.  
  785.   step = sequence[0];
  786.  
  787.   /* Print the header of the header file.  */
  788.  
  789.   printf ("/* Conversion table from `%s' charset to `%s' charset.\n",
  790.       before_full_name, after_full_name);
  791.   printf ("   Generated mechanically by GNU %s %s.\n", PRODUCT, VERSION);
  792.   printf ("\n");
  793.   switch (sequence[0]->quality)
  794.     {
  795.     case REVERSIBLE:
  796.       printf ("   The recoding should be reversible.\n");
  797.       break;
  798.  
  799.     case ONE_TO_ONE:
  800.       printf ("   The recoding might not be reversible.\n");
  801.       break;
  802.  
  803.     case MANY_TO_ONE:
  804.       printf ("   Programming is needed to handle multichar input.\n");
  805.       break;
  806.  
  807.     case ONE_TO_MANY:
  808.       printf ("   Each input char transforms into an output string.\n");
  809.       break;
  810.  
  811.     case MANY_TO_MANY:
  812.       printf ("   Each input char transforms into an output string,\n");
  813.       printf ("   programming is needed to handle multichar input.\n");
  814.       break;
  815.     }
  816.   printf ("*/\n");
  817.   printf ("\n");
  818.  
  819.   /* Construct the name of the resulting table.  */
  820.  
  821.   if (header_name)
  822.     name = xstrdup (header_name);
  823.   else
  824.     {
  825.       name = (char *) xmalloc (strlen (before_full_name) + sizeof "_to_"
  826.                    + strlen (after_full_name));
  827.       strcpy (name, before_full_name);
  828.       strcat (name, "_to_");
  829.       strcat (name, after_full_name);
  830.     }
  831.  
  832.   /* Ensure the table name contains only valid characters for a C
  833.      identifier.  */
  834.  
  835.   for (cursor = name; *cursor; cursor++)
  836.     if (*cursor != '_'
  837.     && (*cursor < 'a' || *cursor > 'z')
  838.     && (*cursor < 'A' || *cursor > 'Z')
  839.     && (*cursor < '0' || *cursor > '9'))
  840.       *cursor = '_';
  841.  
  842.   /* Produce the recoding table in the correct format.  */
  843.  
  844.   if (step->one_to_one)
  845.     {
  846.  
  847.       /* Produce a one to one recoding table.  */
  848.  
  849.       printf ("unsigned char const %s[256] =\n", name);
  850.       printf ("  {\n");
  851.       for (counter = 0; counter < 256; counter++)
  852.     {
  853.       printf ("%s%3d,", counter % 8 == 0 ? "    " : " ",
  854.            step->one_to_one[counter]);
  855.       if (counter % 8 == 7)
  856.         printf ("\t/* %3d - %3d */\n", counter - 7, counter);
  857.     }
  858.       printf ("  };\n");
  859.     }
  860.  
  861.   else if (step->one_to_many)
  862.     {
  863.  
  864.       /* Produce a one to many recoding table.  */
  865.  
  866.       printf ("const char *%s[256] =\n", name);
  867.       printf ("  {\n");
  868.       for (counter = 0; counter < 256; counter++)
  869.     {
  870.       printf ("    ");
  871.       column = 4;
  872.       if (step->one_to_many[counter])
  873.         {
  874.           printf ("\"");
  875.           column++;
  876.           for (cursor2 = step->one_to_many[counter]; *cursor2; cursor2++)
  877.         switch (*cursor2)
  878.           {
  879.           case ' ':
  880.             printf (" ");
  881.             column++;
  882.             break;
  883.  
  884.           case '\b':
  885.             printf ("\\b");
  886.             column += 2;
  887.             break;
  888.  
  889.           case '\t':
  890.             printf ("\\t");
  891.             column += 2;
  892.             break;
  893.  
  894.           case '\n':
  895.             printf ("\\n");
  896.             column += 2;
  897.             break;
  898.  
  899.           case '"':
  900.             printf ("\\\"");
  901.             column += 2;
  902.             break;
  903.  
  904.           case '\\':
  905.             printf ("\\\\");
  906.             column += 2;
  907.             break;
  908.  
  909.           default:
  910.             if (isprint (*cursor2))
  911.               {
  912.             printf ("%c", *cursor2);
  913.             column++;
  914.               }
  915.             else
  916.               {
  917.             printf ("\\%0.3o", *(const unsigned char *) cursor2);
  918.             column += 4;
  919.               }
  920.           }
  921.           printf ("\"");
  922.           column++;
  923.         }
  924.       else
  925.         {
  926.           printf ("0");
  927.           column++;
  928.         }
  929.       printf (",");
  930.       column++;
  931.       while (column < 32)
  932.         {
  933.           printf ("\t");
  934.           column += 8 - column % 8;
  935.         }
  936.       printf ("/* %3d */\n", counter);
  937.     }
  938.       printf ("  };\n");
  939.     }
  940.  
  941.   else
  942.     error (EXIT_FAILURE, 0, "No table to print");
  943.  
  944.   free (name);
  945. }
  946.  
  947. /* Double step handling (for RFC 1345).  */
  948.  
  949. /*-----------------------------------------------------------------------.
  950. | Associate a double TABLE with charset NAME, part of the RFC 1345 fully |
  951. | connected set.  Each entry in table uses SIZE characters.         |
  952. `-----------------------------------------------------------------------*/
  953.  
  954. void
  955. declare_double_step (DOUBLE_TABLE *table, const char *name, int size)
  956. {
  957.   CHARSET *charset;
  958.   STEP *step;
  959.  
  960.   charset = find_charset (name);
  961.   charset->table = table;
  962.   charset->size = size;
  963.  
  964.   step = new_single_step ();
  965.   step->before = charset;
  966.   step->after = rfc1345;
  967.   step->quality = strict_mapping ? ONE_TO_MANY : REVERSIBLE;
  968.   step->init_recode = NULL;
  969.   step->file_recode = NULL;
  970.  
  971.   step = new_single_step ();
  972.   step->before = rfc1345;
  973.   step->after = charset;
  974.   step->quality = strict_mapping ? ONE_TO_MANY : REVERSIBLE;
  975.   step->init_recode = NULL;
  976.   step->file_recode = NULL;
  977. }
  978.  
  979. /*---------------------------------------------------------------.
  980. | Order two struct item's lexicographically of their key value.     |
  981. `---------------------------------------------------------------*/
  982.  
  983. struct item
  984.   {
  985.     const char *key;        /* RFC 1345 short mnemonic name */
  986.     int code;            /* corresponding charset code (0..255) */
  987.   };
  988.  
  989. static int
  990. compare_struct_item (const void *void_first, const void *void_second)
  991. {
  992.   return strcmp (((const struct item *) void_first)->key,
  993.          ((const struct item *) void_second)->key);
  994. }
  995.  
  996. /*------------------------------------------------------------------------.
  997. | Complete the initialization of a double step which just has been merged |
  998. | into a single STEP.  Establish known pairings by comparing keys between |
  999. | the before and after charsets.                      |
  1000. `------------------------------------------------------------------------*/
  1001.  
  1002. void
  1003. init_recode_rfc1345 (STEP *step)
  1004. {
  1005.   struct side
  1006.     {
  1007.       CHARSET *charset;        /* charset */
  1008.       struct item item[256];    /* array of binding items */
  1009.       int number_of_items;    /* number of binding items in array */
  1010.     };
  1011.  
  1012.   char pool[2 * 256 * 6];    /* character pool */
  1013.   DOUBLE_TABLE *table;        /* RFC 1345 table */
  1014.   struct side side_array[2];    /* information for each side */
  1015.   struct side *side;        /* cursor into side_array */
  1016.   int reversed;            /* if both sides reversed */
  1017.   const char *in;        /* cursor in double table strings */
  1018.   char *out;            /* cursor in character pool */
  1019.   int code;            /* character code */
  1020.   int row_counter;        /* double table row counter */
  1021.   int position_counter;        /* double table column counter */
  1022.   int counter;            /* counter for characters */
  1023.   struct item *item_cursor;    /* cursor in arrays of binding items */
  1024.   struct item *left;        /* left binding items cursor */
  1025.   struct item *left_limit;    /* limit value for left */
  1026.   struct item *right;        /* right binding items cursor */
  1027.   struct item *right_limit;    /* limit value for right */
  1028.   KNOWN_PAIR pair_array[256];    /* obtained pairings */
  1029.   KNOWN_PAIR *pair_cursor;    /* cursor in array of pairings */
  1030.   int value;            /* result of lexicographical comparison */
  1031.  
  1032.   /* For ensuring reversibility, known pairs should be computed the same
  1033.      way regardless of the direction of recoding.  This canonalization is
  1034.      ensured through the charset values, which are increasing along the
  1035.      initialization order.  This should also reflect the charset order in
  1036.      rfc1345.txt.  */
  1037.  
  1038.   if (step->before < step->after)
  1039.     {
  1040.       side_array[0].charset = step->before;
  1041.       side_array[1].charset = step->after;
  1042.       reversed = 0;
  1043.     }
  1044.   else
  1045.     {
  1046.       side_array[0].charset = step->after;
  1047.       side_array[1].charset = step->before;
  1048.       reversed = 1;
  1049.     }
  1050.  
  1051.   out = pool;
  1052.   for (side = side_array; side < side_array + 2; side++)
  1053.     {
  1054.  
  1055.       /* Move the string values out of the double table, while constructing
  1056.      the array of binding items for the charset.  */
  1057.  
  1058.       table = side->charset->table;
  1059.       item_cursor = side->item;
  1060.       code = 0;
  1061.  
  1062.       for (row_counter = 0; row_counter < 8; row_counter++)
  1063.     if (in = (*table)[row_counter], in)
  1064.       for (position_counter = 0; position_counter < 32; position_counter++)
  1065.         {
  1066.           if (*in == ' ')
  1067.         in += side->charset->size;
  1068.           else
  1069.         {
  1070.  
  1071.           /* Establish a new binding item.  */
  1072.  
  1073.           item_cursor->code = code;
  1074.           item_cursor->key = out;
  1075.           item_cursor++;
  1076.  
  1077.           /* Copy out the value to the character pool, and terminate it
  1078.              with a NULL.  */
  1079.  
  1080.           for (counter = 0; counter < side->charset->size; counter++)
  1081.             if (*in == ' ')
  1082.               in++;
  1083.             else
  1084.               *out++ = *in++;
  1085.           *out++ = '\0';
  1086.         }
  1087.           code++;
  1088.         }
  1089.     else
  1090.       code += 32;
  1091.  
  1092.       side->number_of_items = item_cursor - side->item;
  1093.     }
  1094.  
  1095.   /* Sort both arrays of binding items into lexicographical order.  The
  1096.      taken time, which is O(n.log(n)), is gained back when the further
  1097.      pairing is completed in a time which is linear instead of quadratic.  */
  1098.  
  1099.   qsort (side_array[0].item, side_array[0].number_of_items,
  1100.      sizeof (struct item), compare_struct_item);
  1101.   qsort (side_array[1].item, side_array[1].number_of_items,
  1102.      sizeof (struct item), compare_struct_item);
  1103.  
  1104.   /* Scan both arrays of binding items simultaneously, saving as pairs
  1105.      those codes having the same key.  */
  1106.  
  1107.   left = side_array[0].item;
  1108.   left_limit = left + side_array[0].number_of_items;
  1109.   right = side_array[1].item;
  1110.   right_limit = right + side_array[1].number_of_items;
  1111.   pair_cursor = pair_array;
  1112.  
  1113.   while (left < left_limit && right < right_limit)
  1114.     {
  1115.       value = strcmp (left->key, right->key);
  1116.       if (value < 0)
  1117.     left++;
  1118.       else if (value > 0)
  1119.     right++;
  1120.       else
  1121.     {
  1122.       pair_cursor->left = (left++)->code;
  1123.       pair_cursor->right = (right++)->code;
  1124.       pair_cursor++;
  1125.     }
  1126.     }
  1127.  
  1128.   /* Complete the recoding table out of this.  */
  1129.  
  1130.   complete_pairs (step, 0, pair_array, pair_cursor - pair_array, reversed);
  1131. }
  1132.  
  1133. /* Step sequence handling.  */
  1134.  
  1135. #define UNREACHABLE    30000        /* No way for this conversion */
  1136.  
  1137. /*-------------------------------------------------------.
  1138. | Explain what recoding step sequence has been planned.     |
  1139. `-------------------------------------------------------*/
  1140.  
  1141. static void
  1142. echo_sequence (void)
  1143. {
  1144.   const char *last;        /* last name printed */
  1145.   const char *name;        /* name being printed */
  1146.   QUALITY quality;        /* cumulative quality */
  1147.   int counter;            /* index into sequence */
  1148.  
  1149.   if (length_of_sequence < 0)
  1150.     fprintf (stderr, "UNACHIEVABLE recoding!\n");
  1151.   else if (length_of_sequence == 0)
  1152.     fprintf (stderr, "Mere copy for the trivial recoding\n");
  1153.   else
  1154.     {
  1155.       quality = REVERSIBLE;
  1156.       last = NULL;
  1157.       for (counter = 0; counter < length_of_sequence; counter++)
  1158.     {
  1159.       name = sequence[counter]->before->name;
  1160.       if (counter == 0)
  1161.         fprintf (stderr, "%s", name);
  1162.       else if (name != last)
  1163.         fprintf (stderr, "/%s", name);
  1164.  
  1165.       name = sequence[counter]->after->name;
  1166.       fprintf (stderr, " -> %s", name);
  1167.  
  1168.       quality = merge_qualities (quality, sequence[counter]->quality);
  1169.       last = name;
  1170.     }
  1171.       fprintf (stderr, " (%s)\n", quality_to_string (quality));
  1172.     }
  1173. }
  1174.  
  1175. /*----------------------------------------------------------.
  1176. | Find a sequence of single steps to achieve a conversion.  |
  1177. `----------------------------------------------------------*/
  1178.  
  1179. static void
  1180. find_sequence (CHARSET *before, CHARSET *after)
  1181. {
  1182.   struct search
  1183.     {
  1184.       STEP *step;        /* step who will bring us nearer to after */
  1185.       int cost;            /* cost from here through after */
  1186.     };
  1187.   struct search *search_array;    /* critical path search tree */
  1188.   struct search *search;    /* item in search_array for charset */
  1189.   STEP *step;            /* cursor in possible single_steps */
  1190.   int cost;            /* cost under consideration */
  1191.   int modified;            /* != 0 if modified since last iteration */
  1192.   CHARSET *charset;        /* charset while reconstructing sequence */
  1193.  
  1194.   search_array
  1195.     = (struct search *) xmalloc (number_of_charsets * sizeof (struct search));
  1196.  
  1197.   /* Initialize the search for an economical route, looking our way
  1198.      backward from the after towards the before.  */
  1199.  
  1200.   for (search = search_array;
  1201.        search < search_array + number_of_charsets;
  1202.        search++)
  1203.     {
  1204.       search->step = NULL;
  1205.       search->cost = UNREACHABLE;
  1206.     }
  1207.   search_array[after - charset_array].cost = 0;
  1208.  
  1209.   modified = 1;
  1210.   while (modified)
  1211.     {
  1212.       modified = 0;
  1213.       for (step = single_step_array;
  1214.        step < single_step_array + number_of_single_steps;
  1215.        step++)
  1216.     if (!step->before->ignore)
  1217.       {
  1218.         cost = search_array[step->after - charset_array].cost;
  1219.         if (cost != UNREACHABLE)
  1220.           {
  1221.         cost += step->conversion_cost;
  1222.         search = search_array + (step->before - charset_array);
  1223.         if (cost < search->cost)
  1224.           {
  1225.             search->step = step;
  1226.             search->cost = cost;
  1227.             modified = 1;
  1228.           }
  1229.           }
  1230.       }
  1231.     }
  1232.  
  1233.   if (search_array[before - charset_array].cost == UNREACHABLE)
  1234.     {
  1235.       
  1236.       /* If no path has been found, return with a negative length.  */
  1237.  
  1238.       length_of_sequence = -1;
  1239.     }
  1240.   else
  1241.     {
  1242.  
  1243.       /* Save the retained best path in the sequence array.  While doing so,
  1244.      simplify out any single step which merely copies.  Also execute the
  1245.      delayed initialization for those steps which registered one.  */
  1246.  
  1247.       length_of_sequence = 0;
  1248.       for (charset = before; charset != after; charset = step->after)
  1249.     {
  1250.       step = search_array[charset - charset_array].step;
  1251.       if (step->file_recode != file_one_to_one
  1252.           || step->one_to_one != one_to_same)
  1253.         {
  1254.           if (length_of_sequence == MAX_SEQUENCE)
  1255.         error (EXIT_FAILURE, 0, "MAX_SEQUENCE is too small");
  1256.           sequence[length_of_sequence++] = step;
  1257.           if (step->init_recode)
  1258.         {
  1259.           (*step->init_recode) (step);
  1260.           step->init_recode = NULL;
  1261.         }
  1262.         }
  1263.     }
  1264.     }
  1265.  
  1266.   /* Tell what has been decided, for the user.  */
  1267.  
  1268.   if (verbose_option)
  1269.     echo_sequence ();
  1270.  
  1271.   free (search_array);
  1272. }
  1273.  
  1274. /*-------------------------------------------------------------------------.
  1275. | Return 0 if STEP cannot be easily simplified.  Return 1 if it is an all  |
  1276. | table driven ONE_TO_ONE recoding.  Return 2 if it is an all table driven |
  1277. | ONE_TO_MANY recoding.  If making headers, accept more easily that a step |
  1278. | is simplifyable, just looking at tables and ignoring preset functions.   |
  1279. `-------------------------------------------------------------------------*/
  1280.  
  1281. static int
  1282. simplify_type (const STEP *step)
  1283. {
  1284.   if (step->one_to_one
  1285.       && (make_header_mode || step->file_recode == file_one_to_one))
  1286.     return 1;
  1287.  
  1288.   if (step->one_to_many
  1289.       && (make_header_mode || step->file_recode == file_one_to_many))
  1290.     return 2;
  1291.  
  1292.   return 0;
  1293. }
  1294.  
  1295. /*---------------------------------------------------------------------.
  1296. | Optimize a sequence of single steps by creating new single steps, if |
  1297. | this can be done by merging adjacent steps which are simple enough.  |
  1298. `---------------------------------------------------------------------*/
  1299.  
  1300. static void
  1301. simplify_sequence (void)
  1302. {
  1303.   int saved_steps;        /* number of saved steps */
  1304.   int in;            /* ordinal of next studied sequence step */
  1305.   int out;            /* ordinal of next output sequence step */
  1306.   STEP *step;            /* new single step being constructed */
  1307.   unsigned char *accum;        /* one_to_one accumulated recoding */
  1308.   const char **string;        /* one_to_many recoding */
  1309.   unsigned char temp[256];    /* temporary value for accum array */
  1310.   int counter;            /* all purpose counter */
  1311.  
  1312.   saved_steps = 0;
  1313.  
  1314.   /* See if there are some RFC 1345 double steps to merge.  */
  1315.  
  1316.   in = 0;
  1317.   out = 0;
  1318.  
  1319.   while (in < length_of_sequence)
  1320.     if (in < length_of_sequence - 1
  1321.     && sequence[in]->after == rfc1345
  1322.     && sequence[in+1]->before == rfc1345)
  1323.       {
  1324.  
  1325.     /* Produce a new single step for the double step.  */
  1326.  
  1327.     step = new_single_step ();
  1328.     step->before = sequence[in]->before;
  1329.     step->after = sequence[in+1]->after;
  1330.     step->quality = merge_qualities (sequence[in]->quality,
  1331.                      sequence[in+1]->quality);
  1332.     step->init_recode = init_recode_rfc1345;
  1333.     step->file_recode = file_one_to_one;
  1334.  
  1335.     in += 2;
  1336.     saved_steps++;
  1337.  
  1338.     /* Initialize the new single step, so it can be later merged with
  1339.        others.  */
  1340.  
  1341.     (*step->init_recode) (step);
  1342.     step->init_recode = NULL;
  1343.  
  1344.     sequence[out++] = step;
  1345.       }
  1346.     else if (sequence[in]->before == rfc1345)
  1347.       error (EXIT_FAILURE, 0, "You may not explicitely recode from RFC 1345");
  1348.     else if (sequence[in]->after == rfc1345)
  1349.       {
  1350.  
  1351.     /* Produce a new single step for the double step.  */
  1352.  
  1353.     step = new_single_step ();
  1354.     step->before = sequence[in]->before;
  1355.     step->after = sequence[in]->after;
  1356.     step->quality = ONE_TO_MANY;
  1357.  
  1358.     in++;
  1359.  
  1360.     /* Initialize the new single step, so it can be later merged with
  1361.        others.  */
  1362.  
  1363.     init_table_for_rfc1345 (step);
  1364.     step->file_recode = file_one_to_many;
  1365.  
  1366.     sequence[out++] = step;
  1367.       }
  1368.     else
  1369.       sequence[out++] = sequence[in++];
  1370.  
  1371.   length_of_sequence = out;
  1372.  
  1373.   /* Recopy the sequence array over itself, while merging subsequences of
  1374.      one or more consecutive one-to-one recodings, including an optional
  1375.      final one-to-many recoding.  */
  1376.  
  1377.   in = 0;
  1378.   out = 0;
  1379.   while (in < length_of_sequence)
  1380.     if (in < length_of_sequence - 1
  1381.     && simplify_type (sequence[in]) == 1
  1382.     && simplify_type (sequence[in+1]) > 0)
  1383.       {
  1384.  
  1385.     /* Construct a new single step, and initialize a cumulative
  1386.        one-to-one recoding with the identity permutation.  */
  1387.  
  1388.     accum = (unsigned char *) xmalloc (256);
  1389.     for (counter = 0; counter < 256; counter++)
  1390.       accum[counter] = counter;
  1391.  
  1392.     step = new_single_step ();
  1393.     step->before = sequence[in]->before;
  1394.     step->quality = REVERSIBLE;
  1395.  
  1396.     /* Merge in all consecutive one-to-one recodings.  */
  1397.  
  1398.     while (in < length_of_sequence && simplify_type (sequence[in]) == 1)
  1399.       {
  1400.         for (counter = 0; counter < 256; counter++)
  1401.           temp[counter] = sequence[in]->one_to_one[accum[counter]];
  1402.         for (counter = 0; counter < 256; counter++)
  1403.           accum[counter] = temp[counter];
  1404.         step->after = sequence[in]->after;
  1405.         step->quality
  1406.           = merge_qualities (step->quality, sequence[in]->quality);
  1407.         in++;
  1408.         saved_steps++;
  1409.       }
  1410.  
  1411.     /* Check for a possible one-to-many recoding.  */
  1412.  
  1413.     if (in < length_of_sequence && simplify_type (sequence[in]) == 2)
  1414.       {
  1415.  
  1416.         /* Merge in the one-to-many recoding, and make the new single
  1417.            step be a one-to-many recoding.  */
  1418.  
  1419.         string = (const char **) xmalloc (256 * sizeof (char *));
  1420.         for (counter = 0; counter < 256; counter++)
  1421.           string[counter] = sequence[in]->one_to_many[accum[counter]];
  1422.         free (accum);
  1423.         step->one_to_many = string;
  1424.         step->file_recode = file_one_to_many;
  1425.         step->after = sequence[in]->after;
  1426.         step->quality
  1427.           = merge_qualities (step->quality, sequence[in]->quality);
  1428.         in++;
  1429.         saved_steps++;
  1430.       }
  1431.     else
  1432.       {
  1433.  
  1434.         /* Make the new single step be a one-to-one recoding.  */
  1435.  
  1436.         step->one_to_one = accum;
  1437.         step->file_recode = file_one_to_one;
  1438.       }
  1439.  
  1440.     /* Save the newly created step.  */
  1441.  
  1442.     sequence[out++] = step;
  1443.       }
  1444.     else
  1445.       sequence[out++] = sequence[in++];
  1446.  
  1447.   length_of_sequence = out;
  1448.  
  1449.   /* Delete a remaining single step, if it happens to be the identity
  1450.      one-to-one recoding.  */
  1451.  
  1452.   if (length_of_sequence == 1 && simplify_type (sequence[0]) == 1
  1453.       && memcmp (sequence[0]->one_to_one, one_to_same, 256) == 0)
  1454.     {
  1455.       length_of_sequence = 0;
  1456.       saved_steps++;
  1457.     }
  1458.  
  1459.   /* Save the resulting sequence length, and tell the user if something
  1460.      changed.  */
  1461.  
  1462.   if (saved_steps > 0 && verbose_option)
  1463.     {
  1464.       fprintf (stderr, "Simplified to: ");
  1465.       echo_sequence ();
  1466.     }
  1467. }
  1468.  
  1469. /* Recoding execution control.  */
  1470.  
  1471. /*--------------.
  1472. | Copy a file.  |
  1473. `--------------*/
  1474.  
  1475. /* This should be rewritten to be a lot faster.  */
  1476.  
  1477. static void
  1478. file_copy (FILE *input_file, FILE *output_file)
  1479. {
  1480.   int input_char;        /* current character */
  1481.  
  1482.   while (input_char = getc (input_file), input_char != EOF)
  1483.     putc (input_char, output_file);
  1484. }
  1485.  
  1486. /*----------------------------------------------------------------------.
  1487. | Recode a file using a one-to-one recoding table.  Returns zero if the |
  1488. | recoding has been interrupted because of a reversibility problem.     |
  1489. `----------------------------------------------------------------------*/
  1490.  
  1491. int
  1492. file_one_to_one (const STEP *step, FILE *input_file, FILE *output_file)
  1493. {
  1494.   const unsigned char *table;    /* conversion table */
  1495.   int input_char;        /* current character */
  1496.  
  1497.   table = step->one_to_one;
  1498.   while (input_char = getc (input_file), input_char != EOF)
  1499.     putc (table[input_char], output_file);
  1500.  
  1501.   return 1;
  1502. }
  1503.  
  1504. /*-----------------------------------------------------------------------.
  1505. | Recode a file using a one-to-many recoding table.  Returns zero if the |
  1506. | recoding has been found to be non reversible.                 |
  1507. `-----------------------------------------------------------------------*/
  1508.  
  1509. int
  1510. file_one_to_many (const STEP *step, FILE *input_file, FILE *output_file)
  1511. {
  1512.   int reversible;        /* reversibility of recoding */
  1513.   const char *const *table;    /* conversion table */
  1514.   int input_char;        /* current character */
  1515.   const char *output_string;    /* translated characters */
  1516.  
  1517.   /* Copy the file through the one to many recoding table.  */
  1518.  
  1519.   reversible = 1;
  1520.   table = step->one_to_many;
  1521.   while (input_char = getc (input_file), input_char != EOF)
  1522.     if (output_string = table[input_char], output_string)
  1523.       while (*output_string)
  1524.     {
  1525.       putc (*output_string, output_file);
  1526.       output_string++;
  1527.     }
  1528.     else
  1529.       reversible = 0;
  1530.  
  1531.   return reversible;
  1532. }
  1533.  
  1534. /*-------------------------------------------------------------------------.
  1535. | Execute the conversion sequence, using several passes with two       |
  1536. | alternating intermediate files.  This routine assumes at least one       |
  1537. | needed recoding step.  Returns zero if the recoding has been found to be |
  1538. | non-reversible.                               |
  1539. `-------------------------------------------------------------------------*/
  1540.  
  1541. static int
  1542. execute_pass_sequence (const char *input_name, const char *output_name)
  1543. {
  1544.   int sequence_index;        /* index into sequence */
  1545.   const STEP *step;        /* pointer to step */
  1546.   FILE *input_file;        /* input file to recoding step */
  1547.   FILE *output_file;        /* output file from recoding step */
  1548.   int reversible;        /* reversibility of recoding */
  1549. #ifdef USE_TMPNAM
  1550.   char *temp_input_name;    /* step input file name */
  1551.   char *temp_output_name;    /* step output file name */
  1552.   char temp_name_1[L_tmpnam];    /* one temporary file name */
  1553.   char temp_name_2[L_tmpnam];    /* another temporary file name */
  1554.   char *exchange_temp;        /* for exchanging temporary names */
  1555. #endif
  1556.  
  1557. #ifdef USE_TMPNAM
  1558.  
  1559.   /* Choose names for intermediate files.  Use "" for delaying them.  */
  1560.  
  1561. #ifdef MSDOS_or_OS2
  1562.   strcpy (temp_name_1, "recodex1.tmp");
  1563.   strcpy (temp_name_2, "recodex2.tmp");
  1564. #else
  1565.   temp_name_1[0] = '\0';
  1566.   temp_name_2[0] = '\0';
  1567. #endif
  1568.   temp_input_name = temp_name_1;
  1569.   temp_output_name = temp_name_2;
  1570.  
  1571. #endif /* USE_TMPNAM */
  1572.  
  1573.   /* Execute one pass for each step of the sequence.  */
  1574.  
  1575.   reversible = 1;
  1576.   for (sequence_index = 0;
  1577.        sequence_index < length_of_sequence;
  1578.        sequence_index++)
  1579.     {
  1580.  
  1581.       /* Select the input file for this step.  */
  1582.  
  1583.       if (sequence_index == 0)
  1584.     {
  1585.       if (!input_name)
  1586.         input_file = stdin;
  1587.       else if (input_file = fopen (input_name, "r"), input_file == NULL)
  1588.         error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1589.            __FILE__, __LINE__, input_name);
  1590.     }
  1591.       else
  1592.     {
  1593. #ifdef USE_TMPNAM
  1594.       if (input_file = fopen (temp_input_name, "r"), input_file == NULL)
  1595.         error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1596.            __FILE__, __LINE__, temp_input_name);
  1597. #endif
  1598.  
  1599. #ifdef USE_TMPFILE
  1600.       rewind (input_file);
  1601. #endif
  1602.     }
  1603.  
  1604.       /* Select the output file for this step.  */
  1605.  
  1606.       if (sequence_index == length_of_sequence - 1)
  1607.     {
  1608.       if (!output_name)
  1609.         output_file = stdout;
  1610.       else if (output_file = fopen (output_name, "w"), output_file == NULL)
  1611.         error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1612.            __FILE__, __LINE__, output_name);
  1613.     }
  1614.       else
  1615.     {
  1616. #ifdef USE_TMPNAM
  1617. #ifdef MSDOS_or_OS2
  1618.       if (*temp_output_name == '\0')
  1619.         tmpnam (temp_output_name);
  1620. #endif
  1621.       if (output_file = fopen (temp_output_name, "w"), output_file == NULL)
  1622.         error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1623.            __FILE__, __LINE__, temp_output_name);
  1624. #endif
  1625.  
  1626. #ifdef USE_TMPFILE
  1627.       if (output_file = tmpfile (), output_file == NULL)
  1628.         error (EXIT_FAILURE, errno, "%s:%d: tmpfile ()",
  1629.            __FILE__, __LINE__);
  1630. #endif
  1631.     }
  1632.  
  1633.       /* Execute one recoding step.  */
  1634.  
  1635.       step = sequence[sequence_index];
  1636.       if (!(*step->file_recode) (step, input_file, output_file))
  1637.     reversible = 0;
  1638.  
  1639.       /* Close the input file, unlink it if it was temporary.  */
  1640.  
  1641.       if (sequence_index == 0)
  1642.     {
  1643.       if (input_name)
  1644.         fclose (input_file);
  1645.     }
  1646.       else
  1647.     {
  1648.       fclose (input_file);
  1649. #ifdef USE_TMPNAM
  1650.       unlink (temp_input_name);
  1651. #endif
  1652.     }
  1653.  
  1654.       /* Close the output file and prepare for subsequent step.  */
  1655.  
  1656.       if (sequence_index == length_of_sequence - 1)
  1657.     {
  1658.       if (output_name)
  1659.         fclose (output_file);
  1660.     }
  1661.       else
  1662.     {
  1663. #ifdef USE_TMPNAM
  1664.       fclose (output_file);
  1665.  
  1666.       exchange_temp = temp_input_name;
  1667.       temp_input_name = temp_output_name;
  1668.       temp_output_name = exchange_temp;
  1669. #endif
  1670.  
  1671. #ifdef USE_TMPFILE
  1672.       input_file = output_file;
  1673. #endif
  1674.     }
  1675.     }
  1676.   return reversible;
  1677. }
  1678.  
  1679. /*-------------------------------------------------------------------------.
  1680. | Execute the conversion sequence, using a chain of invocations of the       |
  1681. | program through popen.  This routine assumes that more than one recoding |
  1682. | step is needed.  Returns zero if the recoding has been found to be       |
  1683. | non-reversible.                               |
  1684. `-------------------------------------------------------------------------*/
  1685.  
  1686. #ifdef HAVE_POPEN
  1687.  
  1688. static int
  1689. execute_popen_sequence (const char *input_name, const char *output_name)
  1690. {
  1691.   const STEP *step;        /* current step */
  1692.   FILE *input_file;        /* input file to recoding step */
  1693.   FILE *output_file;        /* output file from recoding step */
  1694.   char popen_command[80];    /* to receive command string */
  1695.   int reversible;        /* reversibility of recoding */
  1696.  
  1697.   /* Construct a `recode' command for all recoding steps but the first.  */
  1698.  
  1699.   strcpy (popen_command, program_path);
  1700.   if (diaeresis_char)
  1701.     strcat (popen_command, " -c");
  1702.   if (diacritics_only)
  1703.     strcat (popen_command, " -d");
  1704.   if (force_option)
  1705.     strcat (popen_command, " -f");
  1706.   strcat (popen_command, " -o -q ");
  1707.   strcat (popen_command, clean_charset_name (sequence[1]->before->name));
  1708.   strcat (popen_command, ":");
  1709.   strcat (popen_command,
  1710.       clean_charset_name (sequence[length_of_sequence-1]->after->name));
  1711.   if (output_name)
  1712.     {
  1713.       strcat (popen_command, " >");
  1714.       strcat (popen_command, output_name);
  1715.     }
  1716.  
  1717.   /* Execute the first recoding step.  */
  1718.  
  1719.   if (!input_name)
  1720.     input_file = stdin;
  1721.   else if (input_file = fopen (input_name, "r"), input_file == NULL)
  1722.     error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1723.        __FILE__, __LINE__, input_name);
  1724.  
  1725.   if (output_file = popen (popen_command, "w"), output_file == NULL)
  1726.     error (EXIT_FAILURE, errno, "%s:%d: popen (%s)",
  1727.        __FILE__, __LINE__, popen_command);
  1728.  
  1729.   step = sequence[0];
  1730.   reversible = (*step->file_recode) (step, input_file, output_file);
  1731.  
  1732.   if (input_name)
  1733.     fclose (input_file);
  1734.  
  1735.   /* Return the proper status.  */
  1736.  
  1737.   if (pclose (output_file) != 0)
  1738.     reversible = 0;
  1739.  
  1740.   return reversible;
  1741. }
  1742.  
  1743. #endif /* HAVE_POPEN */
  1744.  
  1745. #ifdef HAVE_PIPE
  1746.  
  1747. #ifndef HAVE_DUP2
  1748.  
  1749. /*------------------------------------------------------------------------.
  1750. | Duplicate the OLD_FD file descriptor into NEW_FD, closing NEW_FD first  |
  1751. | if it is used.  This implementation presumes both OLD_FD and NEW_FD are |
  1752. | valid file descriptors.                          |
  1753. `------------------------------------------------------------------------*/
  1754.  
  1755. /* Overall idea taken from GNU Emacs 18.55 dup2 (), in src/sysdep.c.  */
  1756.  
  1757. #include <sys/fcntl.h>
  1758.  
  1759. #ifndef F_DUPFD
  1760.  
  1761. static int
  1762. dup2_recursive (int old_fd, int new_fd)
  1763. {
  1764.   int fd;
  1765.  
  1766.   /* Attempt to dup OLD_FD to NEW_FD.  If not successful, call dup2
  1767.      recursively, filling the file descriptor table until NEW_FD is
  1768.      reached.  Then close all the spurious file descriptors we created.  */
  1769.  
  1770.   if (fd = dup (old_fd) && fd != new_fd)
  1771.     if (fd < 0 || dup2_recursive (old_fd, new_fd) < 0 || close (fd) < 0)
  1772.       return 0;
  1773.  
  1774.   return 1;
  1775. }
  1776.  
  1777. #endif /* not F_DUPFD */
  1778.  
  1779. static int
  1780. dup2 (int old_fd, int new_fd)
  1781. {
  1782.  
  1783.   /* If OLD_FD or NEW_FD were not valid file descriptors, dup2 should
  1784.      ideally return -1 with errno set to EBADF.  This is not checked.  */
  1785.  
  1786.   if (old_fd != new_fd)
  1787.     {
  1788.       close (new_fd);
  1789.  
  1790. #ifdef F_DUPFD
  1791.       if (fcntl (old_fd, F_DUPFD, new_fd) != new_fd)
  1792.     return -1;
  1793. #else
  1794.       if (!dup2_recursive (old_fd, new_fd))
  1795.     return -1;
  1796. #endif
  1797.     }
  1798.   return new_fd;
  1799. }
  1800.  
  1801. #endif /* not HAVE_DUP2 */
  1802.  
  1803. /*-------------------------------------------------------------------------.
  1804. | Execute the conversion sequence, forking the program many times for all  |
  1805. | elementary steps, interconnecting them with pipes.  This routine assumes |
  1806. | that more than one recoding step is needed.  Returns zero if the       |
  1807. | recoding has been found to be non-reversible.                   |
  1808. `-------------------------------------------------------------------------*/
  1809.  
  1810. #if 1
  1811.  
  1812. /* This is no good.  The main process might open too many files for one
  1813.    thing.  All of it should work almost the same way
  1814.    execute_popen_sequence does, creating children from left to right,
  1815.    instead of all children to a single parent right to left.  */
  1816.  
  1817. static int
  1818. execute_pipe_sequence (const char *input_name, const char *output_name)
  1819. {
  1820.   int sequence_index;        /* index into sequence */
  1821.   const STEP *step;        /* pointer into single_steps */
  1822.  
  1823.   FILE *input_file;        /* input file to recoding step */
  1824.   FILE *output_file;        /* output file from recoding step */
  1825.   int pipe_pair[2];        /* pair of file descriptors for a pipe */
  1826.   int child_process;        /* child process number, zero if child */
  1827.   int wait_status;        /* status returned by wait() */
  1828.   int reversible;        /* reversibility of recoding */
  1829.  
  1830.   /* Prepare the final output file.  */
  1831.  
  1832.   if (!output_name)
  1833.     output_file = stdout;
  1834.   else if (output_file = fopen (output_name, "w"), output_file == NULL)
  1835.     error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1836.        __FILE__, __LINE__, output_name);
  1837.  
  1838.   /* Create all subprocesses, from the last to the first, and
  1839.      interconnect them.  */
  1840.  
  1841.   reversible = 1;
  1842.   for (sequence_index = length_of_sequence - 1;
  1843.        sequence_index > 0;
  1844.        sequence_index--)
  1845.     {
  1846.       if (pipe (pipe_pair) < 0)
  1847.     error (EXIT_FAILURE, errno, "%s:%d: pipe ()",
  1848.            __FILE__, __LINE__);
  1849.       if (child_process = fork (), child_process < 0)
  1850.     error (EXIT_FAILURE, errno, "%s:%d: fork ()",
  1851.            __FILE__, __LINE__);
  1852.       if (child_process == 0)
  1853.     {
  1854.  
  1855.           /* The child executes its recoding step, reading from the pipe
  1856.              and writing to the current output file; then it exits.  */
  1857.  
  1858.       if (close (pipe_pair[1]) < 0)
  1859.         error (EXIT_FAILURE, errno, "%s:%d: close ()",
  1860.            __FILE__, __LINE__);
  1861.       if (input_file = fdopen (pipe_pair[0], "r"), input_file == NULL)
  1862.         error (EXIT_FAILURE, errno, "%s:%d: fdopen ()",
  1863.            __FILE__, __LINE__);
  1864.  
  1865.       step = sequence[sequence_index];
  1866.       if (!(*step->file_recode) (step, input_file, output_file))
  1867.         reversible = 0;
  1868.  
  1869.       fclose (input_file);
  1870.       if (sequence_index < length_of_sequence - 1 || output_name)
  1871.         fclose (output_file);
  1872.  
  1873.       exit (reversible ? EXIT_SUCCESS : EXIT_FAILURE);
  1874.     }
  1875.       else
  1876.     {
  1877.  
  1878.           /* The parent redirects the current output file to the pipe.  */
  1879.  
  1880.       if (dup2 (pipe_pair[1], fileno (output_file)) < 0)
  1881.         error (EXIT_FAILURE, errno, "%s:%d: dup2 ()",
  1882.            __FILE__, __LINE__);
  1883.       if (close (pipe_pair[0]) < 0)
  1884.         error (EXIT_FAILURE, errno, "%s:%d: close ()",
  1885.            __FILE__, __LINE__);
  1886.       if (close (pipe_pair[1]) < 0)
  1887.         error (EXIT_FAILURE, errno, "%s:%d: close ()",
  1888.            __FILE__, __LINE__);
  1889.     }
  1890.     }
  1891.  
  1892.   /* All the children are created, blocked on read.  Now, feed the whole
  1893.      chain of processes with the output of the first recoding step.  */
  1894.  
  1895.   if (!input_name)
  1896.     input_file = stdin;
  1897.   else if (input_file = fopen (input_name, "r"), input_file == NULL)
  1898.     error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1899.        __FILE__, __LINE__, input_name);
  1900.  
  1901.   step = sequence[0];
  1902.   if (!(*step->file_recode) (step, input_file, output_file))
  1903.     reversible = 0;
  1904.  
  1905.   if (input_name)
  1906.     fclose (input_file);
  1907.  
  1908.   fclose (output_file);
  1909.  
  1910.   /* Wait on all children, mainly to avoid synchronisation problems on
  1911.      output file contents, but also to reduce the number of zombie
  1912.      processes in case the user recodes many files at once.  */
  1913.  
  1914.   while (wait (&wait_status) > 0)
  1915.     {
  1916.  
  1917.       /* Diagnose and abort on any abnormally terminating child.  */
  1918.  
  1919.       if ((wait_status & ~(~0 << 8)) != 0
  1920.       && (wait_status & ~(~0 << 8)) != SIGPIPE)
  1921.     error (0, 0, "Child process wait status is 0x%0.2x",
  1922.            wait_status);
  1923.  
  1924.       /* Check for a non-zero exit from the terminating child.  */
  1925.  
  1926.       if (wait_status & ~(~0 << 16))
  1927.     reversible = 0;
  1928.     }
  1929.  
  1930.   if (interrupted)
  1931.     reversible = 0;
  1932.  
  1933.   return reversible;
  1934. }
  1935.  
  1936. #else
  1937.  
  1938. static int
  1939. execute_pipe_sequence (const char *input_name, const char *output_name)
  1940. {
  1941.   int sequence_index;        /* index into sequence */
  1942.   const STEP *step;        /* pointer into single_steps */
  1943.  
  1944.   FILE *input_file;        /* input file to recoding step */
  1945.   FILE *output_file;        /* output file from recoding step */
  1946.   int pipe_pair[2];        /* pair of file descriptors for a pipe */
  1947.   int child_process;        /* child process number, zero if child */
  1948.   int wait_status;        /* status returned by wait() */
  1949.   int reversible;        /* reversibility of recoding */
  1950.  
  1951.   /* Prepare the final files.  */
  1952.  
  1953.   if (!input_name)
  1954.     input_file = stdin;
  1955.   else if (input_file = fopen (input_name, "r"), input_file == NULL)
  1956.     error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1957.        __FILE__, __LINE__, input_name);
  1958.  
  1959.   if (!output_name)
  1960.     output_file = stdout;
  1961.   else if (output_file = fopen (output_name, "w"), output_file == NULL)
  1962.     error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  1963.        __FILE__, __LINE__, output_name);
  1964.  
  1965.   /* Create all subprocesses, from the first to the last, and
  1966.      interconnect them.  */
  1967.  
  1968.   reversible = 1;
  1969.   for (sequence_index = 0;
  1970.        sequence_index < length_of_sequence - 1;
  1971.        sequence_index++)
  1972.     {
  1973.       if (pipe (pipe_pair) < 0)
  1974.     error (EXIT_FAILURE, errno, "%s:%d: pipe ()",
  1975.            __FILE__, __LINE__);
  1976.       if (child_process = fork (), child_process < 0)
  1977.     error (EXIT_FAILURE, errno, "%s:%d: fork ()",
  1978.            __FILE__, __LINE__);
  1979.       if (child_process == 0)
  1980.     {
  1981.           /* The child executes its recoding step, reading from the pipe
  1982.              and writing to the current output file; then it exits.  */
  1983.  
  1984.       if (close (pipe_pair[1]) < 0)
  1985.         error (EXIT_FAILURE, errno, "%s:%d: close ()",
  1986.            __FILE__, __LINE__);
  1987.       if (input_file = fdopen (pipe_pair[0], "r"), input_file == NULL)
  1988.         error (EXIT_FAILURE, errno, "%s:%d: fdopen ()",
  1989.            __FILE__, __LINE__);
  1990.  
  1991.       step = sequence[sequence_index];
  1992.       if (!(*step->file_recode) (step, input_file, output_file))
  1993.         reversible = 0;
  1994.  
  1995.       fclose (input_file);
  1996.       if (sequence_index < length_of_sequence - 1 || output_name)
  1997.         fclose (output_file);
  1998.  
  1999.       exit (reversible ? EXIT_SUCCESS : EXIT_FAILURE);
  2000.     }
  2001.       else
  2002.     {
  2003.  
  2004.           /* The parent redirects the current output file to the pipe.  */
  2005.  
  2006.       if (dup2 (pipe_pair[1], fileno (output_file)) < 0)
  2007.         error (EXIT_FAILURE, errno, "%s:%d: dup2 ()",
  2008.            __FILE__, __LINE__);
  2009.       if (close (pipe_pair[0]) < 0)
  2010.         error (EXIT_FAILURE, errno, "%s:%d: close ()",
  2011.            __FILE__, __LINE__);
  2012.       if (close (pipe_pair[1]) < 0)
  2013.         error (EXIT_FAILURE, errno, "%s:%d: close ()",
  2014.            __FILE__, __LINE__);
  2015.     }
  2016.       else
  2017.     {
  2018.       break;
  2019.     }
  2020.     }
  2021.  
  2022.   /* All processes execute the following common code, each with its proper
  2023.      value for SEQUENCE_INDEX, CHILD_PROCESS, etc.  */
  2024.  
  2025.   /* All the children are created, blocked on read.  Now, feed the whole
  2026.      chain of processes with the output of the first recoding step.  */
  2027.  
  2028.   if (!input_name)
  2029.     input_file = stdin;
  2030.   else if (input_file = fopen (input_name, "r"), input_file == NULL)
  2031.     error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  2032.        __FILE__, __LINE__, input_name);
  2033.  
  2034.   step = sequence[0];
  2035.   if (!(*step->file_recode) (step, input_file, output_file))
  2036.     reversible = 0;
  2037.  
  2038.   if (input_name)
  2039.     fclose (input_file);
  2040.  
  2041.   fclose (output_file);
  2042.  
  2043.   /* Wait on all children, mainly to avoid synchronisation problems on
  2044.      output file contents, but also to reduce the number of zombie
  2045.      processes in case the user recodes many files at once.  */
  2046.  
  2047.   while (wait (&wait_status) > 0)
  2048.     {
  2049.  
  2050.       /* Diagnose and abort on any abnormally terminating child.  */
  2051.  
  2052.       if ((wait_status & ~(~0 << 8)) != 0
  2053.       && (wait_status & ~(~0 << 8)) != SIGPIPE)
  2054.     error (0, 0, "Child process wait status is 0x%0.2x",
  2055.            wait_status);
  2056.  
  2057.       /* Check for a non-zero exit from the terminating child.  */
  2058.  
  2059.       if (wait_status & ~(~0 << 16))
  2060.     reversible = 0;
  2061.     }
  2062.  
  2063.   if (interrupted)
  2064.     reversible = 0;
  2065.  
  2066.   return reversible;
  2067. }
  2068.  
  2069. #endif
  2070.  
  2071. #endif /* HAVE_PIPE */
  2072.  
  2073. /*-------------------------------------------------------------------------.
  2074. | Execute the conversion sequence, using the selected strategy whenever       |
  2075. | more than one conversion step is needed.  If no conversion are needed,   |
  2076. | merely copy the input onto the output.  Returns zero if the recoding has |
  2077. | been found to be non-reversible.                       |
  2078. `-------------------------------------------------------------------------*/
  2079.  
  2080. /* If some sequencing strategies are missing, this routine automatically
  2081.    uses fallback strategies.  */
  2082.  
  2083. static int
  2084. execute_sequence (const char *input_name, const char *output_name)
  2085. {
  2086.   FILE *input_file;        /* input file to recoding step */
  2087.   FILE *output_file;        /* output file from recoding step */
  2088.   const STEP *step;        /* current step */
  2089.   int reversible;        /* reversibility of recoding */
  2090.  
  2091. #ifdef MSDOS_or_OS2
  2092.   if (!input_name)
  2093.     setmode (fileno (stdin), O_BINARY);
  2094.   if (!output_name)
  2095.     setmode (fileno (stdout), O_BINARY);
  2096. #ifdef __EMX__
  2097.   {
  2098.     extern int _fmode_bin;
  2099.     _fmode_bin = 1;
  2100.   }
  2101. #else
  2102.   _fmode = O_BINARY;
  2103. #endif
  2104. #endif
  2105.  
  2106.   if (verbose_option && input_name)
  2107.     {
  2108.       fprintf (stderr, "Recoding %s...", input_name);
  2109.       fflush (stderr);
  2110.     }
  2111.  
  2112.   if (length_of_sequence > 1)
  2113.     switch (sequence_strategy)
  2114.       {
  2115.       case STRATEGY_UNDECIDED:
  2116.     error (EXIT_FAILURE, 0, "Internal error - strategy undecided");
  2117.  
  2118.       case SEQUENCE_WITH_PIPE:
  2119. #ifdef HAVE_PIPE
  2120.     reversible = execute_pipe_sequence (input_name, output_name);
  2121.     break;
  2122. #endif
  2123.  
  2124.       case SEQUENCE_WITH_POPEN:
  2125. #ifdef HAVE_POPEN
  2126.     reversible = execute_popen_sequence (input_name, output_name);
  2127.     break;
  2128. #endif
  2129.  
  2130.       case SEQUENCE_WITH_FILES:
  2131.     reversible = execute_pass_sequence (input_name, output_name);
  2132.     break;
  2133.       }
  2134.   else
  2135.     {
  2136.  
  2137.       /* This is a single-step recoding a mere copy.  Do it.  */
  2138.  
  2139.       if (!input_name)
  2140.     input_file = stdin;
  2141.       else if (input_file = fopen (input_name, "r"), input_file == NULL)
  2142.     error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  2143.            __FILE__, __LINE__, input_name);
  2144.  
  2145.       if (!output_name)
  2146.     output_file = stdout;
  2147.       else if (output_file = fopen (output_name, "w"), output_file == NULL)
  2148.     error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  2149.            __FILE__, __LINE__, output_name);
  2150.  
  2151.       if (length_of_sequence == 1)
  2152.     {
  2153.       step = sequence[0];
  2154.       reversible = (*step->file_recode) (step, input_file, output_file);
  2155.     }
  2156.       else
  2157.     {
  2158.       file_copy (input_file, output_file);
  2159.       reversible = 1;
  2160.     }
  2161.  
  2162.       if (input_name)
  2163.     fclose (input_file);
  2164.       if (output_name)
  2165.     fclose (output_file);
  2166.     }
  2167.  
  2168.   if (verbose_option && input_name)
  2169.     {
  2170.       fprintf (stderr, " done\n");
  2171.       fflush (stderr);
  2172.     }
  2173.   return reversible;
  2174. }
  2175.  
  2176. /* Some special option handling.  */
  2177.  
  2178. /*-----------------------------------------------------------------.
  2179. | Print a truncated charset name, with a guaranteed space at end.  |
  2180. `-----------------------------------------------------------------*/
  2181.  
  2182. static void
  2183. print_truncated_charset_name (const char *name)
  2184. {
  2185.   char copy[15];
  2186.  
  2187.   if ((int) strlen (name) > 14)
  2188.     {
  2189.       memcpy (copy, name, 14);
  2190.       copy[14] = '\0';
  2191.       name = copy;
  2192.     }
  2193.   printf ("%-14s ", name);
  2194. }
  2195.  
  2196. /*----------------------------------------------------------------------.
  2197. | Find all possible sequences and report about them.  If CHARSET is not |
  2198. | NULL, limit the study to those recoding starting or ending with the   |
  2199. | given charset.                                |
  2200. `----------------------------------------------------------------------*/
  2201.  
  2202. static void
  2203. perform_auto_check_one (CHARSET *before, CHARSET *after)
  2204. {
  2205.   int saved_length_of_sequence;
  2206.   int saved_number_of_single_steps;
  2207.   QUALITY quality;
  2208.   const char *quality_string;
  2209.   int counter;
  2210.   STEP *step;
  2211.  
  2212.   /* Study what we can do.  */
  2213.  
  2214.   find_sequence (before, after);
  2215.   if (length_of_sequence < 0)
  2216.     {
  2217.       if (!ignored_name)
  2218.     {
  2219.       print_truncated_charset_name (before->name);
  2220.       print_truncated_charset_name (after->name);
  2221.       printf ("  UNACHIEVABLE\n");
  2222.     }
  2223.     }
  2224.   else
  2225.     {
  2226.  
  2227.       /* Compute the recoding quality.  */
  2228.  
  2229.       quality = REVERSIBLE;
  2230.       for (counter = 0; counter < length_of_sequence; counter++)
  2231.     quality = merge_qualities (quality,
  2232.                    sequence[counter]->quality);
  2233.       quality_string = quality_to_string (quality);
  2234.  
  2235.       /* Study what optimization can do.  */
  2236.  
  2237.       saved_length_of_sequence = length_of_sequence;
  2238.       saved_number_of_single_steps = number_of_single_steps;
  2239.  
  2240.       simplify_sequence ();
  2241.  
  2242.       /* Check and report codes which should be aliases.  */
  2243.  
  2244.       if (length_of_sequence == 0)
  2245.     quality_string = "ONE to SAME";
  2246.  
  2247.       /* Make the report.  */
  2248.  
  2249.       print_truncated_charset_name (before->name);
  2250.       print_truncated_charset_name (after->name);
  2251.       printf ("  %-16s", quality_string);
  2252.       printf ("steps: %d", saved_length_of_sequence);
  2253.  
  2254.       if (length_of_sequence != saved_length_of_sequence)
  2255.     printf (", %d saved by merging",
  2256.         saved_length_of_sequence - length_of_sequence);
  2257.       printf ("\n");
  2258.  
  2259.       /* Unregister and clean up the merged steps.  */
  2260.  
  2261.       while (number_of_single_steps > saved_number_of_single_steps)
  2262.     {
  2263.       number_of_single_steps--;
  2264.       step = single_step_array + number_of_single_steps;
  2265.       if (step->one_to_one)
  2266.         free ((void *) step->one_to_one);
  2267.       if (step->one_to_many)
  2268.         free ((void *) step->one_to_many);
  2269.     }
  2270.     }
  2271. }
  2272.  
  2273. static void
  2274. perform_auto_check (CHARSET *charset)
  2275. {
  2276.   CHARSET *before;
  2277.   CHARSET *after;
  2278.  
  2279.   if (charset->ignore)
  2280.     error (EXIT_FAILURE, 0, "Cannot auto check the ignored charset");
  2281.   if (charset == rfc1345)
  2282.     error (EXIT_FAILURE, 0, "Cannot auto check on %s", charset->name);
  2283.  
  2284.   if (charset)
  2285.     {
  2286.       for (before = charset_array;
  2287.        before < charset_array + number_of_charsets;
  2288.        before++)
  2289.     if (!before->ignore && before != charset && before != rfc1345)
  2290.  
  2291.         perform_auto_check_one (before, charset);
  2292.  
  2293.       for (after = charset_array;
  2294.        after < charset_array + number_of_charsets;
  2295.        after++)
  2296.     if (!after->ignore && after != charset && after != rfc1345)
  2297.  
  2298.         perform_auto_check_one (charset, after);
  2299.     }
  2300.   else
  2301.     for (before = charset_array;
  2302.      before < charset_array + number_of_charsets;
  2303.      before++)
  2304.       if (!before->ignore && before != rfc1345)
  2305.  
  2306.     for (after = charset_array;
  2307.          after < charset_array + number_of_charsets;
  2308.          after++)
  2309.       if (!after->ignore && after != before && after != rfc1345)
  2310.  
  2311.         perform_auto_check_one (before, after);
  2312. }
  2313.  
  2314. /* Main program.  */
  2315.  
  2316. /*-----------------------------------------------.
  2317. | Explain how to use the program, then get out.     |
  2318. `-----------------------------------------------*/
  2319.  
  2320. void
  2321. usage (int status)
  2322. {
  2323.   if (status != EXIT_SUCCESS)
  2324.     fprintf (stderr, "Try `%s %s' for more information.\n", program_name,
  2325.          decoding_charset_flag ? "--list" : "--help");
  2326.   else
  2327.     {
  2328.       printf ("GNU %s %s\n", PRODUCT, VERSION);
  2329.       printf ("\
  2330. \n\
  2331. Usage: %s [OPTION]... [CHARSET]\n", program_name);
  2332.       fputs ("\
  2333. Mandatory or optional arguments to long options are mandatory or optional\n\
  2334. for short options too.\n\
  2335. \n\
  2336.   -C, --copyright       display Copyright and copying conditions\n\
  2337.   -a, --auto-check      report about some or all recoding paths, then exit\n\
  2338.   -l, --list[=FORMAT]   list one or all known charsets\n\
  2339.   -k, --known=PAIRS     restrict charsets according to known PAIRS list\n\
  2340.       --help            display this help and exit\n\
  2341.       --version         output version information and exit\n\
  2342. \n\
  2343. FORMAT is a word among decimal, octal, hexadecimal or full (which may be\n\
  2344. abbreviated to one of `dohf'), it defaults to just the canonical name.\n\
  2345. With -k, possible before charsets are listed for the given after CHARSET,\n\
  2346. both being RFC1345 charsets, with PAIRS of the form `BEF1:AFT1,BEF2:AFT2,...\n\
  2347. and BEFs and AFTs being codes.  All codes are given as decimal numbers.\n",
  2348.           stdout);
  2349.       fputs ("\
  2350. Option -l with no FORMAT nor CHARSET list all charsets, also see the Texinfo\n\
  2351. documentation.  My preferred charsets are (each user has preferences):\n\
  2352. \n\
  2353.   ascii-bs   ASCII (7-bit), using backspace to apply diacritics\n\
  2354.   ibmpc      IBM-PC 8-bit characters, with proper newlines\n\
  2355.   latex      LaTeX coding of foreign and diacriticized characters\n\
  2356.   latin1     ISO Latin-1 8-bit extension of ASCII\n\
  2357.   texte      Easy French convention for transmitting email messages\n",
  2358.          stdout);
  2359.       printf ("\
  2360. \n\
  2361. Usage: %s [OPTION]... [BEFORE]:[AFTER] [FILE]...\n", program_name);
  2362.       fputs ("\
  2363. \n\
  2364.   -c, --colons            use colons instead of double quotes for diaeresis\n\
  2365.   -d, --diacritics        limit conversion to diacritics or alike for LaTeX\n\
  2366.   -f, --force             force recodings even if they are not reversible\n\
  2367.                           (BEWARE: in this version, -f is always selected)\n\
  2368.   -g, --graphics          approximate IBMPC rulers by ASCII graphics\n\
  2369.   -h, --header[=NAME]     write C code with table NAME on stdout, then exit\n\
  2370.   -i, --sequence=files    use intermediate files for sequencing passes\n",
  2371.          stdout);
  2372.  
  2373. #ifdef HAVE_POPEN
  2374.       fputs ("\
  2375.   -o, --sequence=popen    use popen machinery for sequencing passes\n",
  2376.          stdout);
  2377. #else
  2378.       fputs ("\
  2379.   -o, --sequence=popen    same as -i (on this system)\n",
  2380.          stdout);
  2381. #endif
  2382.  
  2383. #ifdef HAVE_PIPE
  2384.       fputs ("\
  2385.   -p, --sequence=pipe     use pipe machinery for sequencing passes\n",
  2386.          stdout);
  2387. #else
  2388.       fputs ("\
  2389.   -p, --sequence=pipe     same as -o (on this system)\n",
  2390.          stdout);
  2391. #endif
  2392.  
  2393.       fputs ("\
  2394.   -q, --quiet, --silent   inhibit messages about irreversible recodings\n\
  2395.   -s, --strict            use strict mappings, even loose characters\n\
  2396.   -t, --touch             touch the recoded files after replacement\n\
  2397.   -v, --verbose           explain sequence of steps and report progress\n\
  2398.   -x, --ignore=CHARSET    ignore CHARSET while choosing a recoding path\n\
  2399. \n\
  2400. If none of -i, -o and -p are given, presume -p if no FILE, else -i.\n\
  2401. Each FILE is recoded over itself, destroying the original.  If no\n\
  2402. FILE is specified, then act as a filter and recode stdin to stdout.\n",
  2403.          stdout);
  2404.       printf ("\
  2405. BEFORE and AFTER both default to `%s' when needed.\n", DEFAULT_CHARSET);
  2406.     }
  2407.   exit (status);
  2408. }
  2409.  
  2410. /*----------------------------------------------------------------------.
  2411. | Main program.  Decode ARGC arguments passed through the ARGV array of |
  2412. | strings, then launch execution.                        |
  2413. `----------------------------------------------------------------------*/
  2414.  
  2415. /* Long options equivalences.  */
  2416. static const struct option long_options[] =
  2417. {
  2418.   {"auto-check", no_argument, NULL, 'a'},
  2419.   {"colons", no_argument, NULL, 'c'},
  2420.   {"copyright", no_argument, NULL, 'C'},
  2421.   {"diacritics", no_argument, NULL, 'd'},
  2422.   {"force", no_argument, NULL, 'f'},
  2423.   {"header", optional_argument, NULL, 'h'},
  2424.   {"help", no_argument, &show_help, 1},
  2425.   {"ignore", required_argument, NULL, 'x'},
  2426.   {"list", optional_argument, NULL, 'l'},
  2427.   {"quiet", no_argument, NULL, 'q'},
  2428.   {"sequence", required_argument, NULL, '\n'},
  2429.   {"silent", no_argument, NULL, 'q'},
  2430.   {"strict", no_argument, NULL, 's'},
  2431.   {"touch", no_argument, NULL, 't'},
  2432.   {"verbose", no_argument, NULL, 'v'},
  2433.   {"version", no_argument, &show_version, 1},
  2434.   {0, 0, 0, 0},
  2435. };
  2436.  
  2437. static const char *const format_strings[] =
  2438.   {
  2439.     "decimal",
  2440.     "octal",
  2441.     "hexadecimal",
  2442.     "full",
  2443.     NULL,
  2444.   };
  2445.  
  2446. static const char *const sequence_strings[] =
  2447.   {
  2448.     "files",
  2449.     "popen",
  2450.     "pipe",
  2451.     NULL,
  2452.   };
  2453.  
  2454. int
  2455. main (int argc, char *const *argv)
  2456. {
  2457.   extern int optind;        /* index of argument */
  2458.   int option_char;        /* option character */
  2459.   int reversible;        /* reversibility of all recodings */
  2460.   const char *input_name;    /* input file name */
  2461.   char output_name[200];    /* output file name */
  2462.   FILE *file;            /* file to check or stat */
  2463. #ifdef MSDOS
  2464.   struct ftime stamp_stat;    /* input file time stamps */
  2465. #else /* not MSDOS */
  2466.   struct stat stamp_stat;    /* input file time stamps */
  2467.   time_t stamp_utime[2];    /* recoded file time stamps */
  2468. #endif /* not MSDOS */
  2469.   char *cursor;            /* all purpose cursor */
  2470.  
  2471.   /* Decode command options.  */
  2472.  
  2473.   program_path = argv[0];
  2474.   program_name = strrchr (program_path, '/');
  2475.   program_name = program_name ? program_name + 1 : program_path;
  2476.  
  2477.   if (argc == 1)
  2478.     usage (EXIT_SUCCESS);
  2479.  
  2480.   while (option_char = getopt_long (argc, argv, "aCcdfgh::ik:l::opqstvx:",
  2481.                     long_options, NULL),
  2482.      option_char != EOF)
  2483.     switch (option_char)
  2484.       {
  2485.       default:
  2486.     usage (EXIT_FAILURE);
  2487.  
  2488.       case '\0':
  2489.     break;
  2490.  
  2491.       case '\n':
  2492.     switch (argmatch (optarg, sequence_strings))
  2493.       {
  2494.       case -2:
  2495.         error (0, 0, "Ambiguous sequence `%s'", optarg);
  2496.         usage (EXIT_FAILURE);
  2497.  
  2498.       case -1:
  2499.         error (0, 0, "Unknown sequence `%s'", optarg);
  2500.         usage (EXIT_FAILURE);
  2501.  
  2502.       case 0:
  2503.         sequence_strategy = SEQUENCE_WITH_FILES;
  2504.         break;
  2505.  
  2506.       case 1:
  2507.         sequence_strategy = SEQUENCE_WITH_POPEN;
  2508.         break;
  2509.  
  2510.       case 2:
  2511.         sequence_strategy = SEQUENCE_WITH_PIPE;
  2512.         break;
  2513.       }
  2514.     break;
  2515.  
  2516.       case 'a':
  2517.     auto_check_mode = 1;
  2518.     break;
  2519.  
  2520.       case 'C':
  2521.     fprintf (stderr, "%s", copyright_string);
  2522.     exit (EXIT_SUCCESS);
  2523.  
  2524.       case 'c':
  2525.     diaeresis_char = ':';
  2526.     break;
  2527.  
  2528.       case 'd':
  2529.     diacritics_only = 1;
  2530.     break;
  2531.  
  2532.       case 'f':
  2533.     force_option = 1;
  2534.     break;
  2535.  
  2536.       case 'g':
  2537.     ascii_graphics = 1;
  2538.     break;
  2539.  
  2540.       case 'h':
  2541.     make_header_mode = 1;
  2542.     header_name = optarg;
  2543.     break;
  2544.  
  2545.       case 'i':
  2546.     sequence_strategy = SEQUENCE_WITH_FILES;
  2547.     break;
  2548.  
  2549.       case 'k':
  2550.     decode_known_pairs (optarg);
  2551.     show_restricted_charsets = 1;
  2552.     break;
  2553.  
  2554.       case 'l':
  2555.     show_charsets = 1;
  2556.     if (optarg)
  2557.       switch (argmatch (optarg, format_strings))
  2558.         {
  2559.         case -2:
  2560.           error (0, 0, "Ambiguous format `%s'", optarg);
  2561.           usage (EXIT_FAILURE);
  2562.  
  2563.         case -1:
  2564.           error (0, 0, "Unknown format `%s'", optarg);
  2565.           usage (EXIT_FAILURE);
  2566.  
  2567.         case 0:
  2568.           list_format = DECIMAL_FORMAT;
  2569.           break;
  2570.  
  2571.         case 1:
  2572.           list_format = OCTAL_FORMAT;
  2573.           break;
  2574.  
  2575.         case 2:
  2576.           list_format = HEXADECIMAL_FORMAT;
  2577.           break;
  2578.  
  2579.         case 3:
  2580.           list_format = FULL_FORMAT;
  2581.           break;
  2582.         }
  2583.     break;
  2584.  
  2585.       case 'o':
  2586.     sequence_strategy = SEQUENCE_WITH_POPEN;
  2587.     break;
  2588.  
  2589.       case 'p':
  2590.     sequence_strategy = SEQUENCE_WITH_PIPE;
  2591.     break;
  2592.  
  2593.       case 'q':
  2594.     quiet_mode = 1;
  2595.     break;
  2596.  
  2597.       case 's':
  2598.     strict_mapping = 1;
  2599.     break;
  2600.  
  2601.       case 't':
  2602.     touch_option = 1;
  2603.     break;
  2604.  
  2605.       case 'v':
  2606.     verbose_option = 1;
  2607.     break;
  2608.  
  2609.       case 'x':
  2610.     ignored_name = optarg;
  2611.     break;
  2612.       }
  2613.  
  2614.   if (ascii_graphics && strict_mapping)
  2615.     {
  2616.       error (0, 0, "Currently, -s is ignored when -g is selected");
  2617.       strict_mapping = 0;
  2618.     }
  2619.  
  2620.   if (ascii_graphics || strict_mapping)
  2621.     force_option = 1;
  2622.  
  2623.   /* Process trivial options.  */
  2624.  
  2625.   if (show_version)
  2626.     {
  2627.       printf ("GNU %s %s\n", PRODUCT, VERSION);
  2628.       exit (EXIT_SUCCESS);
  2629.     }
  2630.  
  2631.   if (show_help)
  2632.     usage (EXIT_SUCCESS);
  2633.  
  2634.   /* Register all modules, then set the ignored charset.  */
  2635.  
  2636.   register_all_modules ();
  2637.   make_argmatch_array ();
  2638.  
  2639.   if (ignored_name)
  2640.     find_charset (clean_charset_name (ignored_name))->ignore = 1;
  2641.  
  2642.   /* Process auto check option.  */
  2643.  
  2644.   if (auto_check_mode)
  2645.     {
  2646.       if (optind + 1 < argc)
  2647.     usage (EXIT_FAILURE);
  2648.  
  2649.       /* Accept a possible charset.  */
  2650.  
  2651.       if (optind < argc)
  2652.     perform_auto_check (find_charset (clean_charset_name (argv[optind])));
  2653.       else
  2654.     perform_auto_check (NULL);
  2655.       exit (EXIT_SUCCESS);
  2656.     }
  2657.  
  2658.   /* Process charset listing options.  */
  2659.  
  2660.   if (show_charsets || show_restricted_charsets)
  2661.     {
  2662.       if (optind + 1 < argc)
  2663.     usage (EXIT_FAILURE);
  2664.  
  2665.       /* Select a possible charset and a default format.  */
  2666.  
  2667.       if (optind < argc)
  2668.     list_charset = find_charset (clean_charset_name (argv[optind]));
  2669.       else if (list_format != NO_FORMAT || show_restricted_charsets)
  2670.     list_charset = find_charset (clean_charset_name (NULL));
  2671.       else
  2672.     list_charset = NULL;
  2673.  
  2674.       /* List the charset(s) appropriately.  */
  2675.       
  2676.       if (show_restricted_charsets)
  2677.     list_all_charsets (list_charset);
  2678.       else if (list_charset)
  2679.     if (list_format == FULL_FORMAT)
  2680.       list_full_charset (list_charset);
  2681.     else
  2682.       list_concise_charset (list_charset);
  2683.       else
  2684.     list_all_charsets (NULL);
  2685.  
  2686.       /* Then get out.  */
  2687.  
  2688.       exit (EXIT_SUCCESS);
  2689.     }
  2690.  
  2691.   /* Decode the BEFORE:AFTER argument.  */
  2692.  
  2693.   if (optind + 1 > argc)
  2694.     usage (EXIT_FAILURE);
  2695.  
  2696.   decode_before_after (argv[optind++]);
  2697.  
  2698.   /* Establish the sequence of recoding steps.  */
  2699.  
  2700.   length_of_sequence = 0;
  2701.   find_sequence (before_charset, after_charset);
  2702.   if (length_of_sequence < 0)
  2703.     error (EXIT_FAILURE, 0, "No way to recode from %s to %s",
  2704.        before_charset->name, after_charset->name);
  2705.  
  2706.   simplify_sequence ();
  2707.  
  2708.   /* If we merely want C code, do it and get out.  */
  2709.  
  2710.   if (make_header_mode)
  2711.     {
  2712.       if (length_of_sequence == 0)
  2713.     error (EXIT_FAILURE, 0, "Recoding is trivial, not worth a table");
  2714.       if (length_of_sequence > 1
  2715.       || !(sequence[0]->one_to_one || sequence[0]->one_to_many))
  2716.     error (EXIT_FAILURE, 0, "Recoding is too complex for a mere table");
  2717.  
  2718.       output_header_file ();
  2719.       exit (EXIT_SUCCESS);
  2720.     }
  2721.  
  2722.   /* If the recoding might be not reversible, do not proceed further without
  2723.      --force option.  */
  2724.  
  2725.   /* DO IT!  */
  2726.  
  2727.   /* If there is no input file, act as a filter.  Else, recode all files
  2728.      over themselves.  */
  2729.  
  2730.   setup_signals ();
  2731.  
  2732.   if (optind < argc)
  2733.     {
  2734.  
  2735.       /* When reading and writing files, unless the user selected otherwise,
  2736.      avoid forking and use intermediate files.  */
  2737.  
  2738.       if (sequence_strategy == STRATEGY_UNDECIDED)
  2739.     sequence_strategy = SEQUENCE_WITH_FILES;
  2740.  
  2741.       /* In case files are recoded over themselves and there is no
  2742.          recoding step at all, do not even try to touch the files.  */
  2743.  
  2744.       reversible = 1;
  2745.       if (length_of_sequence > 0)
  2746.  
  2747.     /* Process files, one at a time.  */
  2748.  
  2749.     for (; optind < argc; optind++)
  2750.       {
  2751.         input_name = argv[optind];
  2752.  
  2753.         /* Check if the file can be read and rewritten.  */
  2754.  
  2755.         if (file = fopen (input_name, "r+"), file == NULL)
  2756.           error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  2757.              __FILE__, __LINE__, input_name);
  2758.  
  2759.         /* Save the input file time stamp.  */
  2760.  
  2761.         if (!touch_option)
  2762.           {
  2763. #ifdef MSDOS
  2764.         getftime (fileno (file), &stamp_stat);
  2765. #else
  2766.         fstat (fileno (file), &stamp_stat);
  2767. #endif
  2768.           }
  2769.  
  2770.         fclose (file);
  2771.  
  2772.         /* Choose an output file in the same directory.  */
  2773.  
  2774. #ifdef MSDOS_or_OS2
  2775.  
  2776.         strcpy (output_name, input_name);
  2777.         for (cursor = output_name + strlen (output_name);
  2778.          cursor > output_name && cursor[-1] != '/'
  2779.          && cursor[-1] != '\\' && cursor[-1] != ':';
  2780.          cursor--)
  2781.           ;
  2782.         strcpy (cursor, "recodeXX.TMP");
  2783.  
  2784. #else /* not MSDOS_or_OS2 */
  2785.  
  2786.         strcpy (output_name, input_name);
  2787.         for (cursor = output_name + strlen (output_name);
  2788.          cursor > output_name && cursor[-1] != '/';
  2789.          cursor--)
  2790.           ;
  2791.         sprintf (cursor, "rec%d.tmp", getpid ());
  2792.  
  2793. #endif /* not MSDOS_or_OS2 */
  2794.  
  2795.         /* Recode the file.  */
  2796.  
  2797.         if (!execute_sequence (input_name, output_name))
  2798.           {
  2799.         reversible = 0;
  2800.         if (!quiet_mode)
  2801.           error (0, 0, "%s: Recoding is not reversible", input_name);
  2802.           }
  2803.  
  2804.         /* Move the new file over the original.  */
  2805.  
  2806.         if (unlink (input_name) < 0)
  2807.           error (EXIT_FAILURE, errno, "%s:%d: unlink (%s)",
  2808.              __FILE__, __LINE__, input_name);
  2809. #ifdef HAVE_RENAME
  2810.         if (rename (output_name, input_name) < 0)
  2811.           error (EXIT_FAILURE, errno, "%s:%d: rename (%s, %s)",
  2812.              __FILE__, __LINE__, output_name, input_name);
  2813. #else
  2814.         if (link (output_name, input_name) < 0)
  2815.           error (EXIT_FAILURE, errno, "%s:%d: link (%s, %s)",
  2816.              __FILE__, __LINE__, output_name, input_name);
  2817.         if (unlink (output_name) < 0)
  2818.           error (EXIT_FAILURE, errno, "%s:%d: unlink (%s)",
  2819.              __FILE__, __LINE__, output_name);
  2820. #endif
  2821.  
  2822.         /* Adjust the time stamp for the new file.  */
  2823.  
  2824.         if (!touch_option)
  2825.           {
  2826. #ifdef MSDOS
  2827.         file = fopen (input_name, "r");
  2828.         if (file == NULL)
  2829.           error (EXIT_FAILURE, errno, "%s:%d: fopen (%s)",
  2830.              __FILE__, __LINE__, input_name);
  2831.         setftime (fileno (file), &stamp_stat);
  2832.         fclose (file);
  2833. #else
  2834.         stamp_utime[0] = stamp_stat.st_atime;
  2835.         stamp_utime[1] = stamp_stat.st_mtime;
  2836.         utime (input_name, stamp_utime);
  2837. #endif
  2838.           }
  2839.       }
  2840.     }
  2841.   else
  2842.     {
  2843.  
  2844.       /* When reading stdin and writing stdout, unless the user selected
  2845.          otherwise, fork processes interconnected with pipes.  */
  2846.  
  2847.       if (sequence_strategy == STRATEGY_UNDECIDED)
  2848.     sequence_strategy = SEQUENCE_WITH_PIPE;
  2849.  
  2850.       if (!execute_sequence (NULL, NULL))
  2851.     {
  2852.       reversible = 0;
  2853.       if (!quiet_mode)
  2854.         error (0, 0, "Recoding is not reversible");
  2855.     }
  2856.     }
  2857.  
  2858.   /* Exit with an appropriate status.  */
  2859.  
  2860.   exit ((force_option || reversible) ? EXIT_SUCCESS : EXIT_FAILURE);
  2861. }
  2862.