home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 1 / Atari Mega Archive - Volume 1.iso / gnu / patch / patch.zoo / patch.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-08-10  |  18.6 KB  |  828 lines

  1. char rcsid[] =
  2.     "$Header: patch.c,v 2.0.1.6 88/06/22 20:46:39 lwall Locked $";
  3.  
  4. /* patch - a program to apply diffs to original files
  5.  *
  6.  * Copyright 1986, Larry Wall
  7.  *
  8.  * This program may be copied as long as you don't try to make any
  9.  * money off of it, or pretend that you wrote it.
  10.  *
  11.  * $Log:    patch.c,v $
  12.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  13.  * patch12: rindex() wasn't declared
  14.  * 
  15.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  16.  * patch10: exit code improved.
  17.  * patch10: better support for non-flexfilenames.
  18.  * 
  19.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  20.  * Short replacement caused spurious "Out of sync" message.
  21.  * 
  22.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  23.  * Improved diagnostic on sync error.
  24.  * Moved do_ed_script() to pch.c.
  25.  * 
  26.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  27.  * Fuzz factor caused offset of installed lines.
  28.  * 
  29.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  30.  * Backwards search could terminate prematurely.
  31.  * 
  32.  * Revision 2.0  86/09/17  15:37:32  lwall
  33.  * Baseline for netwide release.
  34.  * 
  35.  * Revision 1.5  86/08/01  20:53:24  lwall
  36.  * Changed some %d's to %ld's.
  37.  * Linted.
  38.  * 
  39.  * Revision 1.4  86/08/01  19:17:29  lwall
  40.  * Fixes for machines that can't vararg.
  41.  * Added fuzz factor.
  42.  * Generalized -p.
  43.  * General cleanup.
  44.  * 
  45.  * 85/08/15 van%ucbmonet@berkeley
  46.  * Changes for 4.3bsd diff -c.
  47.  *
  48.  * Revision 1.3  85/03/26  15:07:43  lwall
  49.  * Frozen.
  50.  * 
  51.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  52.  * Changed pfp->_file to fileno(pfp).
  53.  * 
  54.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  55.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  56.  * Also allow ed output to be suppressed.
  57.  * 
  58.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  59.  * Added -p option from jromine@uci-750a.
  60.  * 
  61.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  62.  * Now checks for normalness of file to patch.
  63.  * 
  64.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  65.  * Added -D (#ifdef) option from joe@fluke.
  66.  * 
  67.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  68.  * Made smarter about SCCS subdirectories.
  69.  * 
  70.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  71.  * Added -l switch to do loose string comparison.
  72.  * 
  73.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  74.  * Failed hunk count not reset on multiple patch file.
  75.  * 
  76.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  77.  * Branch for sdcrdcf changes.
  78.  * 
  79.  * Revision 1.2  84/11/29  13:29:51  lwall
  80.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  81.  * multiple calls to mktemp().  Will now work on machines that can only
  82.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  83.  * Various cosmetic changes.
  84.  * 
  85.  * Revision 1.1  84/11/09  17:03:58  lwall
  86.  * Initial revision
  87.  * 
  88.  */
  89.  
  90. #include "INTERN.h"
  91. #include "common.h"
  92. #include "EXTERN.h"
  93. #include "version.h"
  94. #include "util.h"
  95. #include "pch.h"
  96. #include "inp.h"
  97.  
  98. /* procedures */
  99.  
  100. void reinitialize_almost_everything();
  101. void get_some_switches();
  102. LINENUM locate_hunk();
  103. void abort_hunk();
  104. void apply_hunk();
  105. void init_output();
  106. void init_reject();
  107. void copy_till();
  108. void spew_output();
  109. void dump_line();
  110. bool patch_match();
  111. bool similar();
  112. void re_input();
  113. void my_exit();
  114.  
  115. /* Apply a set of diffs as appropriate. */
  116.  
  117. main(argc,argv)
  118. int argc;
  119. char **argv;
  120. {
  121.     LINENUM where;
  122.     LINENUM newwhere;
  123.     LINENUM fuzz;
  124.     LINENUM mymaxfuzz;
  125.     int hunk = 0;
  126.     int failed = 0;
  127.     int failtotal = 0;
  128.     int i;
  129. #ifdef TOS
  130.     _binmode(1);
  131.     stdin->_flag |= _IOBIN;    /* sorry! */
  132. #endif
  133.     setbuf(stderr, serrbuf);
  134.     for (i = 0; i<MAXFILEC; i++)
  135.     filearg[i] = Nullch;
  136.     Mktemp(TMPOUTNAME);
  137.     Mktemp(TMPINNAME);
  138.     Mktemp(TMPREJNAME);
  139.     Mktemp(TMPPATNAME);
  140.  
  141.     /* parse switches */
  142.     Argc = argc;
  143.     Argv = argv;
  144.     get_some_switches();
  145.     
  146.     /* make sure we clean up /tmp in case of disaster */
  147.     set_signals(0);
  148.  
  149.     for (
  150.     open_patch_file(filearg[1]);
  151.     there_is_another_patch();
  152.     reinitialize_almost_everything()
  153.     ) {                    /* for each patch in patch file */
  154.  
  155.     if (outname == Nullch)
  156.         outname = savestr(filearg[0]);
  157.     
  158.     /* initialize the patched file */
  159.     if (!skip_rest_of_patch)
  160.         init_output(TMPOUTNAME);
  161.     
  162.     /* for ed script just up and do it and exit */
  163.     if (diff_type == ED_DIFF) {
  164.         do_ed_script();
  165.         continue;
  166.     }
  167.     
  168.     /* initialize reject file */
  169.     init_reject(TMPREJNAME);
  170.     
  171.     /* find out where all the lines are */
  172.     if (!skip_rest_of_patch)
  173.         scan_input(filearg[0]);
  174.     
  175.     /* from here on, open no standard i/o files, because malloc */
  176.     /* might misfire and we can't catch it easily */
  177.     
  178.     /* apply each hunk of patch */
  179.     hunk = 0;
  180.     failed = 0;
  181.     out_of_mem = FALSE;
  182.     while (another_hunk()) {
  183.         hunk++;
  184.         fuzz = Nulline;
  185.         mymaxfuzz = pch_context();
  186.         if (maxfuzz < mymaxfuzz)
  187.         mymaxfuzz = maxfuzz;
  188.         if (!skip_rest_of_patch) {
  189.         do {
  190.             where = locate_hunk(fuzz);
  191.             if (hunk == 1 && where == Nulline && !force) {
  192.                         /* dwim for reversed patch? */
  193.             if (!pch_swap()) {
  194.                 if (fuzz == Nulline)
  195.                 say1(
  196. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  197.                 continue;
  198.             }
  199.             reverse = !reverse;
  200.             where = locate_hunk(fuzz);  /* try again */
  201.             if (where == Nulline) {        /* didn't find it swapped */
  202.                 if (!pch_swap())         /* put it back to normal */
  203.                 fatal1("Lost hunk on alloc error!\n");
  204.                 reverse = !reverse;
  205.             }
  206.             else if (noreverse) {
  207.                 if (!pch_swap())         /* put it back to normal */
  208.                 fatal1("Lost hunk on alloc error!\n");
  209.                 reverse = !reverse;
  210.                 say1(
  211. "Ignoring previously applied (or reversed) patch.\n");
  212.                 skip_rest_of_patch = TRUE;
  213.             }
  214.             else {
  215.                 ask3(
  216. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  217.                 reverse ? "R" : "Unr",
  218.                 reverse ? "Assume" : "Ignore");
  219.                 if (*buf == 'n') {
  220.                 ask1("Apply anyway? [n] ");
  221.                 if (*buf != 'y')
  222.                     skip_rest_of_patch = TRUE;
  223.                 where = Nulline;
  224.                 reverse = !reverse;
  225.                 if (!pch_swap())  /* put it back to normal */
  226.                     fatal1("Lost hunk on alloc error!\n");
  227.                 }
  228.             }
  229.             }
  230.         } while (!skip_rest_of_patch && where == Nulline &&
  231.             ++fuzz <= mymaxfuzz);
  232.  
  233.         if (skip_rest_of_patch) {        /* just got decided */
  234.             Fclose(ofp);
  235.             ofp = Nullfp;
  236.         }
  237.         }
  238.  
  239.         newwhere = pch_newfirst() + last_offset;
  240.         if (skip_rest_of_patch) {
  241.         abort_hunk();
  242.         failed++;
  243.         if (verbose)
  244.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  245.         }
  246.         else if (where == Nulline) {
  247.         abort_hunk();
  248.         failed++;
  249.         if (verbose)
  250.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  251.         }
  252.         else {
  253.         apply_hunk(where);
  254.         if (verbose) {
  255.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  256.             if (fuzz)
  257.             say2(" with fuzz %ld", fuzz);
  258.             if (last_offset)
  259.             say3(" (offset %ld line%s)",
  260.                 last_offset, last_offset==1L?"":"s");
  261.             say1(".\n");
  262.         }
  263.         }
  264.     }
  265.  
  266.     if (out_of_mem && using_plan_a) {
  267.         Argc = Argc_last;
  268.         Argv = Argv_last;
  269.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  270.         continue;
  271.     }
  272.     
  273.     assert(hunk);
  274.     
  275.     /* finish spewing out the new file */
  276.     if (!skip_rest_of_patch)
  277.         spew_output();
  278.     
  279.     /* and put the output where desired */
  280.     ignore_signals();
  281.     if (!skip_rest_of_patch) {
  282.         if (move_file(TMPOUTNAME, outname) < 0) {
  283.         toutkeep = TRUE;
  284.         chmod(TMPOUTNAME, filemode);
  285.         }
  286.         else
  287.         chmod(outname, filemode);
  288.     }
  289.     Fclose(rejfp);
  290.     rejfp = Nullfp;
  291.     if (failed) {
  292.         failtotal += failed;
  293.         if (!*rejname) {
  294.         Strcpy(rejname, outname);
  295. #ifndef FLEXFILENAMES
  296.         {
  297.             char *rindex();
  298.             char *s = rindex(rejname,'/');
  299.  
  300.             if (!s)
  301.             s = rejname;
  302.             if (strlen(s) > 13)
  303.             if (s[12] == '.')    /* try to preserve difference */
  304.                 s[12] = s[13];    /* between .h, .c, .y, etc. */
  305.             s[13] = '\0';
  306.         }
  307. #endif
  308.         Strcat(rejname, REJEXT);
  309.         }
  310.         if (skip_rest_of_patch) {
  311.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  312.             failed, hunk, rejname);
  313.         }
  314.         else {
  315.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  316.             failed, hunk, rejname);
  317.         }
  318.         if (move_file(TMPREJNAME, rejname) < 0)
  319.         trejkeep = TRUE;
  320.     }
  321.     set_signals(1);
  322.     }
  323.     my_exit(failtotal);
  324. }
  325.  
  326. /* Prepare to find the next patch to do in the patch file. */
  327.  
  328. void
  329. reinitialize_almost_everything()
  330. {
  331.     re_patch();
  332.     re_input();
  333.  
  334.     input_lines = 0;
  335.     last_frozen_line = 0;
  336.  
  337.     filec = 0;
  338.     if (filearg[0] != Nullch && !out_of_mem) {
  339.     free(filearg[0]);
  340.     filearg[0] = Nullch;
  341.     }
  342.  
  343.     if (outname != Nullch) {
  344.     free(outname);
  345.     outname = Nullch;
  346.     }
  347.  
  348.     last_offset = 0;
  349.  
  350.     diff_type = 0;
  351.  
  352.     if (revision != Nullch) {
  353.     free(revision);
  354.     revision = Nullch;
  355.     }
  356.  
  357.     reverse = FALSE;
  358.     skip_rest_of_patch = FALSE;
  359.  
  360.     get_some_switches();
  361.  
  362.     if (filec >= 2)
  363.     fatal1("You may not change to a different patch file.\n");
  364. }
  365.  
  366. /* Process switches and filenames up to next '+' or end of list. */
  367.  
  368. void
  369. get_some_switches()
  370. {
  371.     Reg1 char *s;
  372.  
  373.     rejname[0] = '\0';
  374.     Argc_last = Argc;
  375.     Argv_last = Argv;
  376.     if (!Argc)
  377.     return;
  378.     for (Argc--,Argv++; Argc; Argc--,Argv++) {
  379.     s = Argv[0];
  380.     if (strEQ(s, "+")) {
  381.         return;            /* + will be skipped by for loop */
  382.     }
  383.     if (*s != '-' || !s[1]) {
  384.         if (filec == MAXFILEC)
  385.         fatal1("Too many file arguments.\n");
  386.         filearg[filec++] = savestr(s);
  387.     }
  388.     else {
  389.         switch (*++s) {
  390.         case 'b':
  391.         origext = savestr(Argv[1]);
  392.         Argc--,Argv++;
  393.         break;
  394.         case 'B':
  395.         origprae = savestr(Argv[1]);
  396.         Argc--,Argv++;
  397.         break;
  398.         case 'c':
  399.         diff_type = CONTEXT_DIFF;
  400.         break;
  401.         case 'd':
  402.         if (!*++s) {
  403.             Argc--,Argv++;
  404.             s = Argv[0];
  405.         }
  406.         if (chdir(s) < 0)
  407.             fatal2("Can't cd to %s.\n", s);
  408.         break;
  409.         case 'D':
  410.             do_defines = TRUE;
  411.         if (!*++s) {
  412.             Argc--,Argv++;
  413.             s = Argv[0];
  414.         }
  415.         if (!isalpha(*s))
  416.             fatal1("Argument to -D not an identifier.\n");
  417.         Sprintf(if_defined, "#ifdef %s\n", s);
  418.         Sprintf(not_defined, "#ifndef %s\n", s);
  419.         Sprintf(end_defined, "#endif /* %s */\n", s);
  420.         break;
  421.         case 'e':
  422.         diff_type = ED_DIFF;
  423.         break;
  424.         case 'f':
  425.         force = TRUE;
  426.         break;
  427.         case 'F':
  428.         if (*++s == '=')
  429.             s++;
  430.         maxfuzz = atoi(s);
  431.         break;
  432.         case 'l':
  433.         canonicalize = TRUE;
  434.         break;
  435.         case 'n':
  436.         diff_type = NORMAL_DIFF;
  437.         break;
  438.         case 'N':
  439.         noreverse = TRUE;
  440.         break;
  441.         case 'o':
  442.         outname = savestr(Argv[1]);
  443.         Argc--,Argv++;
  444.         break;
  445.         case 'p':
  446.         if (*++s == '=')
  447.             s++;
  448.         strippath = atoi(s);
  449.         break;
  450.         case 'r':
  451.         Strcpy(rejname, Argv[1]);
  452.         Argc--,Argv++;
  453.         break;
  454.         case 'R':
  455.         reverse = TRUE;
  456.         break;
  457.         case 's':
  458.         verbose = FALSE;
  459.         break;
  460.         case 'S':
  461.         skip_rest_of_patch = TRUE;
  462.         break;
  463.         case 'v':
  464.         version();
  465.         break;
  466. #ifdef DEBUGGING
  467.         case 'x':
  468.         debug = atoi(s+1);
  469.         break;
  470. #endif
  471.         default:
  472.         fatal2("Unrecognized switch: %s\n", Argv[0]);
  473.         }
  474.     }
  475.     }
  476. }
  477.  
  478. /* Attempt to find the right place to apply this hunk of patch. */
  479.  
  480. LINENUM
  481. locate_hunk(fuzz)
  482. LINENUM fuzz;
  483. {
  484.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  485.     Reg2 LINENUM offset;
  486.     LINENUM pat_lines = pch_ptrn_lines();
  487.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  488.                 - pat_lines + 1; 
  489.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  490.                 + pch_context();
  491.  
  492.     if (!pat_lines)            /* null range matches always */
  493.     return first_guess;
  494.     if (max_neg_offset >= first_guess)    /* do not try lines < 0 */
  495.     max_neg_offset = first_guess - 1;
  496.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  497.     return first_guess;
  498.     for (offset = 1; ; offset++) {
  499.     Reg5 bool check_after = (offset <= max_pos_offset);
  500.     Reg6 bool check_before = (offset <= max_neg_offset);
  501.  
  502.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  503. #ifdef DEBUGGING
  504.         if (debug & 1)
  505.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  506. #endif
  507.         last_offset = offset;
  508.         return first_guess+offset;
  509.     }
  510.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  511. #ifdef DEBUGGING
  512.         if (debug & 1)
  513.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  514. #endif
  515.         last_offset = -offset;
  516.         return first_guess-offset;
  517.     }
  518.     else if (!check_before && !check_after)
  519.         return Nulline;
  520.     }
  521. }
  522.  
  523. /* We did not find the pattern, dump out the hunk so they can handle it. */
  524.  
  525. void
  526. abort_hunk()
  527. {
  528.     Reg1 LINENUM i;
  529.     Reg2 LINENUM pat_end = pch_end();
  530.     /* add in last_offset to guess the same as the previous successful hunk */
  531.     LINENUM oldfirst = pch_first() + last_offset;
  532.     LINENUM newfirst = pch_newfirst() + last_offset;
  533.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  534.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  535.     char *stars = (diff_type == NEW_CONTEXT_DIFF ? " ****" : "");
  536.     char *minuses = (diff_type == NEW_CONTEXT_DIFF ? " ----" : " -----");
  537.  
  538.     fprintf(rejfp, "***************\n");
  539.     for (i=0; i<=pat_end; i++) {
  540.     switch (pch_char(i)) {
  541.     case '*':
  542.         if (oldlast < oldfirst)
  543.         fprintf(rejfp, "*** 0%s\n", stars);
  544.         else if (oldlast == oldfirst)
  545.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  546.         else
  547.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  548.         break;
  549.     case '=':
  550.         if (newlast < newfirst)
  551.         fprintf(rejfp, "--- 0%s\n", minuses);
  552.         else if (newlast == newfirst)
  553.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  554.         else
  555.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  556.         break;
  557.     case '\n':
  558.         fprintf(rejfp, "%s", pfetch(i));
  559.         break;
  560.     case ' ': case '-': case '+': case '!':
  561.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  562.         break;
  563.     default:
  564.         say1("Fatal internal error in abort_hunk().\n"); 
  565.         abort();
  566.     }
  567.     }
  568. }
  569.  
  570. /* We found where to apply it (we hope), so do it. */
  571.  
  572. void
  573. apply_hunk(where)
  574. LINENUM where;
  575. {
  576.     Reg1 LINENUM old = 1;
  577.     Reg2 LINENUM lastline = pch_ptrn_lines();
  578.     Reg3 LINENUM new = lastline+1;
  579. #define OUTSIDE 0
  580. #define IN_IFNDEF 1
  581. #define IN_IFDEF 2
  582. #define IN_ELSE 3
  583.     Reg4 int def_state = OUTSIDE;
  584.     Reg5 bool R_do_defines = do_defines;
  585.     Reg6 LINENUM pat_end = pch_end();
  586.  
  587.     where--;
  588.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  589.     new++;
  590.     
  591.     while (old <= lastline) {
  592.     if (pch_char(old) == '-') {
  593.         copy_till(where + old - 1);
  594.         if (R_do_defines) {
  595.         if (def_state == OUTSIDE) {
  596.             fputs(not_defined, ofp);
  597.             def_state = IN_IFNDEF;
  598.         }
  599.         else if (def_state == IN_IFDEF) {
  600.             fputs(else_defined, ofp);
  601.             def_state = IN_ELSE;
  602.         }
  603.         fputs(pfetch(old), ofp);
  604.         }
  605.         last_frozen_line++;
  606.         old++;
  607.     }
  608.     else if (new > pat_end)
  609.         break;
  610.     else if (pch_char(new) == '+') {
  611.         copy_till(where + old - 1);
  612.         if (R_do_defines) {
  613.         if (def_state == IN_IFNDEF) {
  614.             fputs(else_defined, ofp);
  615.             def_state = IN_ELSE;
  616.         }
  617.         else if (def_state == OUTSIDE) {
  618.             fputs(if_defined, ofp);
  619.             def_state = IN_IFDEF;
  620.         }
  621.         }
  622.         fputs(pfetch(new), ofp);
  623.         new++;
  624.     }
  625.     else {
  626.         if (pch_char(new) != pch_char(old)) {
  627.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  628.             pch_hunk_beg() + old,
  629.             pch_hunk_beg() + new);
  630. #ifdef DEBUGGING
  631.         say3("oldchar = '%c', newchar = '%c'\n",
  632.             pch_char(old), pch_char(new));
  633. #endif
  634.         my_exit(1);
  635.         }
  636.         if (pch_char(new) == '!') {
  637.         copy_till(where + old - 1);
  638.         if (R_do_defines) {
  639.            fputs(not_defined, ofp);
  640.            def_state = IN_IFNDEF;
  641.         }
  642.         while (pch_char(old) == '!') {
  643.             if (R_do_defines) {
  644.             fputs(pfetch(old), ofp);
  645.             }
  646.             last_frozen_line++;
  647.             old++;
  648.         }
  649.         if (R_do_defines) {
  650.             fputs(else_defined, ofp);
  651.             def_state = IN_ELSE;
  652.         }
  653.         while (pch_char(new) == '!') {
  654.             fputs(pfetch(new), ofp);
  655.             new++;
  656.         }
  657.         if (R_do_defines) {
  658.             fputs(end_defined, ofp);
  659.             def_state = OUTSIDE;
  660.         }
  661.         }
  662.         else {
  663.         assert(pch_char(new) == ' ');
  664.         old++;
  665.         new++;
  666.         }
  667.     }
  668.     }
  669.     if (new <= pat_end && pch_char(new) == '+') {
  670.     copy_till(where + old - 1);
  671.     if (R_do_defines) {
  672.         if (def_state == OUTSIDE) {
  673.             fputs(if_defined, ofp);
  674.         def_state = IN_IFDEF;
  675.         }
  676.         else if (def_state == IN_IFNDEF) {
  677.         fputs(else_defined, ofp);
  678.         def_state = IN_ELSE;
  679.         }
  680.     }
  681.     while (new <= pat_end && pch_char(new) == '+') {
  682.         fputs(pfetch(new), ofp);
  683.         new++;
  684.     }
  685.     }
  686.     if (R_do_defines && def_state != OUTSIDE) {
  687.     fputs(end_defined, ofp);
  688.     }
  689. }
  690.  
  691. /* Open the new file. */
  692.  
  693. void
  694. init_output(name)
  695. char *name;
  696. {
  697.     ofp = fopen(name, "w");
  698.     if (ofp == Nullfp)
  699.     fatal2("patch: can't create %s.\n", name);
  700. }
  701.  
  702. /* Open a file to put hunks we can't locate. */
  703.  
  704. void
  705. init_reject(name)
  706. char *name;
  707. {
  708.     rejfp = fopen(name, "w");
  709.     if (rejfp == Nullfp)
  710.     fatal2("patch: can't create %s.\n", name);
  711. }
  712.  
  713. /* Copy input file to output, up to wherever hunk is to be applied. */
  714.  
  715. void
  716. copy_till(lastline)
  717. Reg1 LINENUM lastline;
  718. {
  719.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  720.  
  721.     if (R_last_frozen_line > lastline)
  722.     say1("patch: misordered hunks! output will be garbled.\n");
  723.     while (R_last_frozen_line < lastline) {
  724.     dump_line(++R_last_frozen_line);
  725.     }
  726.     last_frozen_line = R_last_frozen_line;
  727. }
  728.  
  729. /* Finish copying the input file to the output file. */
  730.  
  731. void
  732. spew_output()
  733. {
  734. #ifdef DEBUGGING
  735.     if (debug & 256)
  736.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  737. #endif
  738.     if (input_lines)
  739.     copy_till(input_lines);        /* dump remainder of file */
  740.     Fclose(ofp);
  741.     ofp = Nullfp;
  742. }
  743.  
  744. /* Copy one line from input to output. */
  745.  
  746. void
  747. dump_line(line)
  748. LINENUM line;
  749. {
  750.     Reg1 char *s;
  751.     Reg2 char R_newline = '\n';
  752.  
  753.     /* Note: string is not null terminated. */
  754.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  755. }
  756.  
  757. /* Does the patch pattern match at line base+offset? */
  758.  
  759. bool
  760. patch_match(base, offset, fuzz)
  761. LINENUM base;
  762. LINENUM offset;
  763. LINENUM fuzz;
  764. {
  765.     Reg1 LINENUM pline = 1 + fuzz;
  766.     Reg2 LINENUM iline;
  767.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  768.  
  769.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  770.     if (canonicalize) {
  771.         if (!similar(ifetch(iline, (offset >= 0)),
  772.              pfetch(pline),
  773.              pch_line_len(pline) ))
  774.         return FALSE;
  775.     }
  776.     else if (strnNE(ifetch(iline, (offset >= 0)),
  777.            pfetch(pline),
  778.            pch_line_len(pline) ))
  779.         return FALSE;
  780.     }
  781.     return TRUE;
  782. }
  783.  
  784. /* Do two lines match with canonicalized white space? */
  785.  
  786. bool
  787. similar(a,b,len)
  788. Reg1 char *a;
  789. Reg2 char *b;
  790. Reg3 int len;
  791. {
  792.     while (len) {
  793.     if (isspace(*b)) {        /* whitespace (or \n) to match? */
  794.         if (!isspace(*a))        /* no corresponding whitespace? */
  795.         return FALSE;
  796.         while (len && isspace(*b) && *b != '\n')
  797.         b++,len--;        /* skip pattern whitespace */
  798.         while (isspace(*a) && *a != '\n')
  799.         a++;            /* skip target whitespace */
  800.         if (*a == '\n' || *b == '\n')
  801.         return (*a == *b);    /* should end in sync */
  802.     }
  803.     else if (*a++ != *b++)        /* match non-whitespace chars */
  804.         return FALSE;
  805.     else
  806.         len--;            /* probably not necessary */
  807.     }
  808.     return TRUE;            /* actually, this is not reached */
  809.                     /* since there is always a \n */
  810. }
  811.  
  812. /* Exit with cleanup. */
  813.  
  814. void
  815. my_exit(status)
  816. int status;
  817. {
  818.     Unlink(TMPINNAME);
  819.     if (!toutkeep) {
  820.     Unlink(TMPOUTNAME);
  821.     }
  822.     if (!trejkeep) {
  823.     Unlink(TMPREJNAME);
  824.     }
  825.     Unlink(TMPPATNAME);
  826.     exit(status);
  827. }
  828.