home *** CD-ROM | disk | FTP | other *** search
/ Club Amiga de Montreal - CAM / CAM_CD_1.iso / files / 317a.lha / RCS / diff / diff3.c < prev    next >
C/C++ Source or Header  |  1989-12-05  |  42KB  |  1,487 lines

  1. /* Three-way file comparison program (diff3) for Project GNU
  2.    Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18.  
  19. /* Written by Randy Smith */
  20.  
  21. /* 
  22.  * Include files.
  23.  */
  24. #include <stdio.h>
  25. #include <ctype.h>
  26.  
  27. #if defined(USG) || defined(AMIGA)
  28. /* Define needed BSD functions in terms of sysV library.  */
  29.  
  30. #define bcopy(s,d,n)    memcpy((d),(s),(n))
  31. #define bcmp(s1,s2,n)    memcmp((s1),(s2),(n))
  32. #define bzero(s,n)    memset((s),0,(n))
  33. #endif
  34.  
  35. #ifdef USG
  36. #define dup2(f,t)    (close(t),fcntl((f),F_DUPFD,(t)))
  37.  
  38. #define vfork    fork
  39. #define index    strchr
  40. #define rindex    strrchr
  41. #endif
  42. /*
  43.  * Internal data structures and macros for the diff3 program; includes
  44.  * data structures for both diff3 diffs and normal diffs.
  45.  */
  46.  
  47. /*
  48.  * Different files within a diff
  49.  */
  50. #define    FILE0    0
  51. #define    FILE1    1
  52. #define    FILE2    2
  53.  
  54. /*
  55.  * Three way diffs are build out of two two-way diffs; the file which
  56.  * the two two-way diffs share is:
  57.  */
  58. #define    FILEC    FILE0
  59.  
  60. /* The ranges are indexed by */
  61. #define    START    0
  62. #define    END    1
  63.  
  64. enum diff_type {
  65.   ERROR,            /* Should not be used */
  66.   ADD,                /* Two way diff add */
  67.   CHANGE,            /* Two way diff change */
  68.   DELETE,            /* Two way diff delete */
  69.   DIFF_ALL,            /* All three are different */
  70.   DIFF_1ST,            /* Only the first is different */
  71.   DIFF_2ND,            /* Only the second */
  72.   DIFF_3RD            /* Only the third */
  73. };
  74.  
  75. /* Two-way diff */
  76. struct diff_block {
  77.   int ranges[2][2];            /* Ranges are inclusive */
  78.   char **lines[2];        /* The actual lines (may contain nulls) */
  79.   int *lengths[2];        /* The lengths of the lines (since nulls) */
  80.   struct diff_block *next;
  81. };
  82.  
  83. /* Three-way diff */
  84.  
  85. struct diff3_block {
  86.   enum diff_type correspond;    /* Type of diff */
  87.   int ranges[3][2];            /* Ranges are inclusive */
  88.   char **lines[3];        /* The actual lines (may contain nulls) */
  89.   int *lengths[3];        /* The lengths of the lines (since nulls) */
  90.   struct diff3_block *next;
  91. };
  92.  
  93. /*
  94.  * Access the ranges on a diff block.
  95.  */
  96. #define    D_LOWLINE(diff, filenum)    \
  97.   ((diff)->ranges[filenum][START])
  98. #define    D_HIGHLINE(diff, filenum)    \
  99.   ((diff)->ranges[filenum][END])
  100. #define    D_NUMLINES(diff, filenum)    \
  101.   (D_HIGHLINE((diff), (filenum)) - D_LOWLINE((diff), (filenum)) + 1)
  102.  
  103. /*
  104.  * Access the line numbers in a file in a diff by absolute line number
  105.  * (i.e. line number within the original file).  Note that these are
  106.  * lvalues and can be used for assignment.
  107.  */
  108. #define    D_LINENUM(diff, filenum, linenum)    \
  109.   (*((diff)->lines[filenum] + linenum - D_LOWLINE((diff), (filenum))))
  110. #define    D_LINELEN(diff, filenum, linenum)    \
  111.   (*((diff)->lengths[filenum] + linenum - D_LOWLINE((diff), (filenum))))
  112.  
  113. /*
  114.  * Access the line numbers in a file in a diff by relative line
  115.  * numbers (i.e. line number within the diff itself).  Note that these
  116.  * are lvalues and can be used for assignment.
  117.  */
  118. #define    D_RELNUM(diff, filenum, linenum)    \
  119.   (*((diff)->lines[filenum] + linenum))
  120. #define    D_RELLEN(diff, filenum, linenum)    \
  121.   (*((diff)->lengths[filenum] + linenum))
  122.  
  123. /*
  124.  * And get at them directly, when that should be necessary.
  125.  */
  126. #define    D_LINEARRAY(diff, filenum)    \
  127.   ((diff)->lines[filenum])
  128. #define    D_LENARRAY(diff, filenum)    \
  129.   ((diff)->lengths[filenum])
  130.  
  131. /*
  132.  * Next block.
  133.  */
  134. #define    D_NEXT(diff)    ((diff)->next)
  135.  
  136. /*
  137.  * Access the type of a diff3 block.
  138.  */
  139. #define    D3_TYPE(diff)    ((diff)->correspond)
  140.  
  141. /*
  142.  * Line mappings based on diffs.  The first maps off the top of the
  143.  * diff, the second off of the bottom.
  144.  */
  145. #define    D_HIGH_MAPLINE(diff, fromfile, tofile, lineno)    \
  146.   ((lineno)                        \
  147.    - D_HIGHLINE ((diff), (fromfile))            \
  148.    + D_HIGHLINE ((diff), (tofile)))
  149.  
  150. #define    D_LOW_MAPLINE(diff, fromfile, tofile, lineno)    \
  151.   ((lineno)                        \
  152.    - D_LOWLINE ((diff), (fromfile))            \
  153.    + D_LOWLINE ((diff), (tofile)))
  154.  
  155. /*
  156.  * General memory allocation function.
  157.  */
  158. #define    ALLOCATE(number, type)    \
  159.   (type *) xmalloc ((number) * sizeof (type))
  160.  
  161. /*
  162.  * Options variables for flags set on command line.
  163.  *
  164.  * EDSCRIPT: Write out an ed script instead of the standard diff3 format.
  165.  *
  166.  * FLAGGING: Indicates that in the case of overlapping diffs (type
  167.  * DIFF_ALL), the lines which would normally be deleted from file 1
  168.  * should be preserved with a special flagging mechanism.
  169.  *
  170.  * DONT_WRITE_OVERLAP: 1 if information for overlapping diffs should
  171.  * not be output.
  172.  *
  173.  * DONT_WRITE_SIMPLE: 1 if information for non-overlapping diffs
  174.  * should not be output. 
  175.  *
  176.  * FINALWRITE: 1 if a :wq should be included at the end of the script
  177.  * to write out the file being edited.
  178.  */
  179. #define DIFF_PROGRAM "rcs:diff"
  180.  
  181. int edscript;
  182. int flagging;
  183. int dont_write_overlap;
  184. int dont_write_simple;
  185. int finalwrite;
  186. int overlaps; 
  187. extern int optind;
  188.  
  189. char *argv0;
  190.  
  191. /*
  192.  * Forward function declarations.
  193.  */
  194. struct diff_block *process_diff ();
  195. struct diff3_block *make_3way_diff ();
  196. void output_diff3 ();
  197. void output_diff3_edscript ();
  198. void usage ();
  199. void fatal ();
  200. void perror_with_exit ();
  201.  
  202. struct diff3_block *using_to_diff3_block ();
  203. int copy_stringlist ();
  204. struct diff3_block *create_diff3_block ();
  205. int compare_line_list ();
  206.  
  207. int read_diff ();
  208. enum diff_type process_diff_control ();
  209. char *scan_diff_line ();
  210.  
  211. struct diff3_block *reverse_diff3_blocklist ();
  212.  
  213. void *xmalloc ();
  214. void *xrealloc ();
  215.  
  216. /*
  217.  * No options take arguments.  "i" is my own addition; it stands for
  218.  * "include write command", to emulate system V behavior.
  219.  */
  220. #define    ARGSTRING    "eix3EX"
  221.  
  222. char diff_program[] = DIFF_PROGRAM;
  223.  
  224. /*
  225.  * Main program.  Calls diff twice on two pairs of input files,
  226.  * combines the two diffs, and outputs them.
  227.  */
  228. main (argc, argv)
  229.      int argc;
  230.      char **argv;
  231. {
  232.   int c;
  233.   int mapping [3];
  234.   int shiftmap;
  235.   int incompat;
  236.   struct diff_block *thread1, *thread2;
  237.   struct diff3_block *diff;
  238.  
  239.   edscript = flagging = dont_write_overlap
  240.     = dont_write_simple = finalwrite = 0;
  241.   incompat = shiftmap = 0;
  242.  
  243.   argv0 = argv[0];
  244.   
  245.   while ((c = getopt (argc, argv, ARGSTRING)) != EOF)
  246.     {
  247.       edscript = 1;
  248.       switch (c)
  249.     {
  250.     case 'x':
  251.       dont_write_simple = 1;
  252.       incompat++;
  253.       break;
  254.     case '3':
  255.       dont_write_overlap = 1;
  256.       incompat++;
  257.       break;
  258.     case 'i':
  259.       finalwrite = 1;
  260.       incompat++;
  261.       break;
  262.     case 'X':
  263.       dont_write_simple = 1;
  264.       /* Falls through */
  265.     case 'E':
  266.       flagging = 1;
  267.       /* Falls through */
  268.     case 'e':
  269.       incompat++;
  270.       break;
  271.     case '?':
  272.     default:
  273.       usage ();
  274.       /* NOTREACHED */
  275.     }
  276.     }
  277.  
  278.   if (incompat > 1)        /* Make sure you only have one of a */
  279.                 /* set of arguments */
  280.     usage ();
  281.   
  282.   if (argc - optind != 3)
  283.     usage ();
  284.  
  285.   if (*argv[optind] == '-' && *(argv[optind] + 1) == '\0')
  286.     {
  287.       /* Sigh.  We've got standard input as the first arg. We can't */
  288.       /* call diff twice on stdin */
  289.       mapping [0] = 1;
  290.       mapping [1] = 2;
  291.       mapping [2] = 0;
  292.       shiftmap = 1;
  293.     }
  294.   else
  295.     {
  296.       /* Normal, what you'd expect */
  297.       mapping [0] = 0;
  298.       mapping [1] = 1;
  299.       mapping [2] = 2;
  300.       shiftmap = 0;
  301.     }
  302.  
  303.   if (shiftmap)
  304.     {
  305.       thread1 = process_diff (argv[optind + 2], argv[optind]);
  306.       thread2 = process_diff (argv[optind + 2], argv[optind + 1]);
  307.     }
  308.   else
  309.     {
  310.       thread1 = process_diff (argv[optind], argv[optind + 1]);
  311.       thread2 = process_diff (argv[optind], argv[optind + 2]);
  312.     }
  313.   diff = make_3way_diff (thread1, thread2);
  314.   if (edscript)
  315.     output_diff3_edscript (stdout, diff, mapping, argv[optind],
  316.                argv[optind + 1], argv[optind + 2]);
  317.   else
  318.     output_diff3 (stdout, diff, mapping);
  319.   exit (overlaps);
  320. }
  321.       
  322. /*
  323.  * Explain, patiently and kindly, how to use this program.  Then exit.
  324.  */
  325. void
  326. usage ()
  327. {
  328.   fprintf (stderr, "Usage:\t%s [ -exEX3 ] [ -i ] file1 file2 file3\n",
  329.        argv0);
  330.   fprintf (stderr, "\tOnly one of [exEX3] allowed\n");
  331.   exit (1);
  332. }
  333.  
  334. /*
  335.  * Routines that combine the two diffs together into one.  The
  336.  * algorithm used follows:
  337.  *
  338.  *   File0 is shared in common between the two diffs.
  339.  *   Diff01 is the diff between 0 and 1.
  340.  *   Diff02 is the diff between 0 and 2.
  341.  *
  342.  *     1) Find the range for the first block in File0.
  343.  *          a) Take the lowest of the two ranges (in File0) in the two
  344.  *             current blocks (one from each diff) as being the low
  345.  *             water mark.  Assign the upper end of this block as
  346.  *             being the high water mark and move the current block up
  347.  *             one.  Mark the block just moved over as to be used.
  348.  *        b) Check the next block in the diff that the high water
  349.  *             mark is *not* from.  
  350.  *           
  351.  *           *If* the high water mark is above
  352.  *             the low end of the range in that block, 
  353.  * 
  354.  *               mark that block as to be used and move the current
  355.  *                 block up.  Set the high water mark to the max of
  356.  *                 the high end of this block and the current.  Repeat b.
  357.  * 
  358.  *       2) Find the corresponding ranges in Files1 (from the blocks
  359.  *          in diff01; line per line outside of diffs) and in File2.
  360.  *          Create a diff3_block, reserving space as indicated by the ranges.
  361.  *        
  362.  *     3) Copy all of the pointers for file0 in.  At least for now,
  363.  *          do bcmp's between corresponding strings in the two diffs.
  364.  *        
  365.  *     4) Copy all of the pointers for file1 and 2 in.  Get what you
  366.  *          need from file0 (when there isn't a diff block, it's
  367.  *          identical to file0 within the range between diff blocks).
  368.  *        
  369.  *     5) If the diff blocks you used came from only one of the two
  370.  *         strings of diffs, then that file (i.e. the one other than
  371.  *         file 0 in that diff) is the odd person out.  If you used
  372.  *         diff blocks from both sets, check to see if files 1 and 2 match:
  373.  *        
  374.  *            Same number of lines?  If so, do a set of bcmp's (if a
  375.  *          bcmp matches; copy the pointer over; it'll be easier later
  376.  *          if you have to do any compares).  If they match, 1 & 2 are
  377.  *          the same.  If not, all three different.
  378.  * 
  379.  *   Then you do it again, until you run out of blocks. 
  380.  * 
  381.  */
  382.  
  383. /* 
  384.  * This routine makes a three way diff (chain of diff3_block's) from two
  385.  * two way diffs (chains of diff_block's).  It is assumed that each of
  386.  * the two diffs passed are off of the same file (i.e. that each of the
  387.  * diffs were made "from" the same file).  The three way diff pointer
  388.  * returned will have numbering 0--the common file, 1--the other file
  389.  * in diff1, and 2--the other file in diff2.
  390.  */
  391. struct diff3_block *
  392. make_3way_diff (thread1, thread2)
  393.      struct diff_block *thread1, *thread2;
  394. {
  395. /*
  396.  * This routine works on the two diffs passed to it as threads.
  397.  * Thread number 0 is diff1, thread number 1 is diff2.  The USING
  398.  * array is set to the base of the list of blocks to be used to
  399.  * construct each block of the three way diff; if no blocks from a
  400.  * particular thread are to be used, that element of the using array
  401.  * is set to 0.  The elements LAST_USING array are set to the last
  402.  * elements on each of the using lists.
  403.  *
  404.  * The HIGH_WATER_MARK is set to the highest line number in File 0
  405.  * described in any of the diffs in either of the USING lists.  The
  406.  * HIGH_WATER_THREAD names the thread.  Similarly the BASE_WATER_MARK
  407.  * and BASE_WATER_THREAD describe the lowest line number in File 0
  408.  * described in any of the diffs in either of the USING lists.  The
  409.  * HIGH_WATER_DIFF is the diff from which the HIGH_WATER_MARK was
  410.  * taken. 
  411.  *
  412.  * The HIGH_WATER_DIFF should always be equal to LAST_USING
  413.  * [HIGH_WATER_THREAD].  The OTHER_DIFF is the next diff to check for
  414.  * higher water, and should always be equal to
  415.  * CURRENT[HIGH_WATER_THREAD ^ 0x1].  The OTHER_THREAD is the thread
  416.  * in which the OTHER_DIFF is, and hence should always be equal to
  417.  * HIGH_WATER_THREAD ^ 0x1.
  418.  *
  419.  * The variable LAST_DIFF is kept set to the last diff block produced
  420.  * by this routine, for line correspondence purposes between that diff
  421.  * and the one currently being worked on.  It is initialized to
  422.  * ZERO_DIFF before any blocks have been created.
  423.  */
  424.  
  425.   struct diff_block
  426.     *using[2],
  427.     *last_using[2],
  428.     *current[2];
  429.  
  430.   int
  431.     high_water_mark,
  432.     base_water_mark;
  433.  
  434.   int
  435.     high_water_thread,
  436.     base_water_thread,
  437.     other_thread;
  438.  
  439.   struct diff_block
  440.     *high_water_diff,
  441.     *other_diff;
  442.  
  443.   struct diff3_block
  444.     *result,
  445.     *tmpblock,
  446.     *result_last,
  447.     *last_diff;
  448.  
  449.   static struct diff3_block zero_diff = {
  450.       ERROR,
  451.       { {0, 0}, {0, 0}, {0, 0} },
  452.       { (char **) 0, (char **) 0, (char **) 0 },
  453.       { (int *) 0, (int *) 0, (int *) 0 },
  454.       (struct diff3_block *) 0
  455.       };
  456.  
  457.   /* Initialization */
  458.   result = result_last = (struct diff3_block *) 0;
  459.   current[0] = thread1; current[1] = thread2;
  460.   last_diff = &zero_diff;
  461.  
  462.   /* Sniff up the threads until we reach the end */
  463.  
  464.   while (current[0] || current[1])
  465.     {
  466.       using[0] = using[1] = last_using[0] = last_using[1] =
  467.     (struct diff_block *) 0;
  468.  
  469.       /* Setup low and high water threads, diffs, and marks */
  470.       if (!current[0])
  471.     base_water_thread = 1;
  472.       else if (!current[1])
  473.     base_water_thread = 0;
  474.       else
  475.     base_water_thread =
  476.       (D_LOWLINE (current[0], FILE0)
  477.        > D_LOWLINE (current[1], FILE0));
  478.       high_water_thread = base_water_thread;
  479.       
  480.       high_water_diff = current[high_water_thread];
  481.     
  482.       /* low and high waters start off same diff */
  483.       base_water_mark = D_LOWLINE (high_water_diff, FILE0);
  484.  
  485.       high_water_mark = D_HIGHLINE (high_water_diff, FILE0);
  486.  
  487.       /* Make the diff you just got info from into the using class */
  488.       using[high_water_thread]
  489.     = last_using[high_water_thread]
  490.     = high_water_diff;
  491.       current[high_water_thread] = high_water_diff->next;
  492.       last_using[high_water_thread]->next
  493.     = (struct diff_block *) 0;
  494.  
  495.       /* And mark the other diff */
  496.       other_thread = high_water_thread ^ 0x1;
  497.       other_diff = current[other_thread];
  498.  
  499.       /* Shuffle up the ladder, checking the other diff to see if it
  500.          needs to be incorporated */
  501.       while (other_diff
  502.          && D_LOWLINE (other_diff, FILE0) <= high_water_mark + 1)
  503.     {
  504.  
  505.       /* Incorporate this diff into the using list.  Note that
  506.          this doesn't take it off the current list */
  507.       if (using[other_thread])
  508.         last_using[other_thread]->next = other_diff;
  509.       else
  510.         using[other_thread] = other_diff;
  511.       last_using[other_thread] = other_diff;
  512.  
  513.       /* Take it off the current list.  Note that this following
  514.          code assumes that other_diff enters it equal to
  515.          current[high_water_thread ^ 0x1] */
  516.       current[other_thread]
  517.         = current[other_thread]->next;
  518.       other_diff->next
  519.         = (struct diff_block *) 0;
  520.  
  521.       /* Set the high_water stuff
  522.          If this comparison is equal, then this is the last pass
  523.          through this loop; since diff blocks within a given
  524.          thread cannot overlap, the high_water_mark will be
  525.          *below* the range_start of either of the next diffs. */
  526.  
  527.       if (high_water_mark < D_HIGHLINE (other_diff, FILE0))
  528.         {
  529.           high_water_thread ^= 1;
  530.           high_water_diff = other_diff;
  531.           high_water_mark = D_HIGHLINE (other_diff, FILE0);
  532.         }
  533.  
  534.       /* Set the other diff */
  535.       other_thread = high_water_thread ^ 0x1;
  536.       other_diff = current[other_thread];
  537.     }
  538.  
  539.       /* The using lists contain a list of all of the blocks to be
  540.          included in this diff3_block.  Create it.  */
  541.  
  542.       tmpblock = using_to_diff3_block (using, last_using,
  543.                        base_water_thread, high_water_thread,
  544.                        last_diff);
  545.  
  546.       if (!tmpblock)
  547.     fatal ("internal: screwup in format of diff blocks");
  548.  
  549.       /* Put it on the list */
  550.       if (result)
  551.     result_last->next = tmpblock;
  552.       else
  553.     result = tmpblock;
  554.       result_last = tmpblock;
  555.  
  556.       /* Setup corresponding lines correctly */
  557.       last_diff = tmpblock;
  558.     }
  559.   return result;
  560. }
  561.  
  562. /*
  563.  * using_to_diff3_block:
  564.  *   This routine takes two lists of blocks (from two separate diff
  565.  * threads) and puts them together into one diff3 block.
  566.  * It then returns a pointer to this diff3 block or 0 for failure.
  567.  *
  568.  * All arguments besides using are for the convenience of the routine;
  569.  * they could be derived from the using array.
  570.  * LAST_USING is a pair of pointers to the last blocks in the using
  571.  * structure.
  572.  * LOW_THREAD and HIGH_THREAD tell which threads contain the lowest
  573.  * and highest line numbers for File0.
  574.  * last_diff contains the last diff produced in the calling routine.
  575.  * This is used for lines mappings which would still be identical to
  576.  * the state that diff ended in.
  577.  *
  578.  * A distinction should be made in this routine between the two diffs
  579.  * that are part of a normal two diff block, and the three diffs that
  580.  * are part of a diff3_block.
  581.  */
  582. struct diff3_block *
  583. using_to_diff3_block (using, last_using, low_thread, high_thread, last_diff)
  584.      struct diff_block
  585.        *using[2],
  586.        *last_using[2];
  587.      int low_thread, high_thread;
  588.      struct diff3_block *last_diff;
  589. {
  590.   int lowc, highc, low1, high1, low2, high2;
  591.   struct diff3_block *result;
  592.   struct diff_block *ptr;
  593.   int i;
  594.   int current0line;
  595.   
  596.   /* Find the range in file0 */
  597.   lowc = using[low_thread]->ranges[0][START];
  598.   highc = last_using[high_thread]->ranges[0][END];
  599.  
  600.   /* Find the ranges in the other files.
  601.      If using[x] is null, that means that the file to which that diff
  602.      refers is equivalent to file 0 over this range */
  603.   
  604.   if (using[0])
  605.     {
  606.       low1 = D_LOW_MAPLINE (using[0], FILE0, FILE1, lowc);
  607.       high1 = D_HIGH_MAPLINE (last_using[0], FILE0, FILE1, highc); 
  608.     }
  609.   else
  610.     {
  611.       low1 = D_HIGH_MAPLINE (last_diff, FILEC, FILE1, lowc);
  612.       high1 = D_HIGH_MAPLINE (last_diff, FILEC, FILE1, highc);
  613.     }
  614.  
  615.   /*
  616.    * Note that in the following, we use file 1 relative to the diff,
  617.    * and file 2 relative to the corresponding lines struct.
  618.    */
  619.   if (using[1])
  620.     {
  621.       low2 = D_LOW_MAPLINE (using[1], FILE0, FILE1, lowc);
  622.       high2 = D_HIGH_MAPLINE (last_using[1], FILE0, FILE1, highc); 
  623.     }
  624.   else
  625.     {
  626.       low2 = D_HIGH_MAPLINE (last_diff, FILEC, FILE2, lowc);
  627.       high2 = D_HIGH_MAPLINE (last_diff, FILEC, FILE2, highc);
  628.     }
  629.  
  630.   /* Create a block with the appropriate sizes */
  631.   result = create_diff3_block (lowc, highc, low1, high1, low2, high2);
  632.  
  633.   /* Copy over all of the information for File 0.  Return with a zero
  634.      if any of the compares failed. */
  635.   for (ptr = using[0]; ptr; ptr = D_NEXT (ptr))
  636.     {
  637.       int result_offset = D_LOWLINE (ptr, FILE0) - lowc;
  638.       int copy_size
  639.     = D_HIGHLINE (ptr, FILE0) - D_LOWLINE (ptr, FILE0) + 1;
  640.       
  641.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE0),
  642.                 D_LENARRAY (ptr, FILE0),
  643.                 D_LINEARRAY (result, FILEC) + result_offset,
  644.                 D_LENARRAY (result, FILEC) + result_offset,
  645.                 copy_size))
  646.     return 0;
  647.     }
  648.  
  649.   for (ptr = using[1]; ptr; ptr = D_NEXT (ptr))
  650.     {
  651.       int result_offset = D_LOWLINE (ptr, FILEC) - lowc;
  652.       int copy_size
  653.     = D_HIGHLINE (ptr, FILEC) - D_LOWLINE (ptr, FILEC) + 1;
  654.       
  655.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE0),
  656.                 D_LENARRAY (ptr, FILE0),
  657.                 D_LINEARRAY (result, FILEC) + result_offset,
  658.                 D_LENARRAY (result, FILEC) + result_offset,
  659.                 copy_size))
  660.     return 0;
  661.     }
  662.  
  663.   /* Copy stuff for file 1.  First deal with anything that might be
  664.      before the first diff. */
  665.  
  666.   for (i = 0;
  667.        i + low1 < (using[0] ? D_LOWLINE (using[0], FILE1) : high1 + 1);
  668.        i++)
  669.     {
  670.       D_RELNUM (result, FILE1, i) = D_RELNUM (result, FILEC, i);
  671.       D_RELLEN (result, FILE1, i) = D_RELLEN (result, FILEC, i);
  672.     }
  673.   
  674.   for (ptr = using[0]; ptr; ptr = D_NEXT (ptr))
  675.     {
  676.       int result_offset = D_LOWLINE (ptr, FILE1) - low1;
  677.       int copy_size
  678.     = D_HIGHLINE (ptr, FILE1) - D_LOWLINE (ptr, FILE1) + 1;
  679.  
  680.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE1),
  681.                 D_LENARRAY (ptr, FILE1),
  682.                 D_LINEARRAY (result, FILE1) + result_offset,
  683.                 D_LENARRAY (result, FILE1) + result_offset,
  684.                 copy_size))
  685.     return 0;
  686.  
  687.       /* Catch the lines between here and the next diff */
  688.       current0line = D_HIGHLINE (ptr, FILE0) + 1 - lowc;
  689.       for (i = D_HIGHLINE (ptr, FILE1) + 1 - low1;
  690.        i < (D_NEXT (ptr) ?
  691.         D_LOWLINE (D_NEXT (ptr), FILE1) :
  692.         high1 + 1) - low1;
  693.        i++)
  694.     {
  695.       D_RELNUM (result, FILE1, i)
  696.         = D_RELNUM (result, FILEC, current0line);
  697.       D_RELLEN (result, FILE1, i)
  698.         = D_RELLEN (result, FILEC, current0line++);
  699.     }
  700.     }
  701.  
  702.   /* Copy stuff for file 2.  First deal with anything that might be
  703.      before the first diff. */
  704.  
  705.   for (i = 0;
  706.        i + low2 < (using[1] ? D_LOWLINE (using[1], FILE1) : high2 + 1);
  707.        i++)
  708.     {
  709.       D_RELNUM (result, FILE2, i) = D_RELNUM (result, FILEC, i);
  710.       D_RELLEN (result, FILE2, i) = D_RELLEN (result, FILEC, i);
  711.     }
  712.   
  713.   for (ptr = using[1]; ptr; ptr = D_NEXT (ptr))
  714.     {
  715.       int result_offset = D_LOWLINE (ptr, FILE1) - low2;
  716.       int copy_size
  717.     = D_HIGHLINE (ptr, FILE1) - D_LOWLINE (ptr, FILE1) + 1;
  718.  
  719.       if (!copy_stringlist (D_LINEARRAY (ptr, FILE1),
  720.                 D_LENARRAY (ptr, FILE1),
  721.                 D_LINEARRAY (result, FILE2) + result_offset,
  722.                 D_LENARRAY (result, FILE2) + result_offset,
  723.                 copy_size))
  724.     return 0;
  725.  
  726.       /* Catch the lines between here and the next diff */
  727.       current0line = D_HIGHLINE (ptr, FILE0) + 1 - lowc;
  728.       for (i = D_HIGHLINE (ptr, FILE1) + 1 - low2;
  729.        i < (D_NEXT (ptr) ?
  730.         D_LOWLINE (D_NEXT (ptr), FILE1) :
  731.         high2 + 1) - low2;
  732.        i++)
  733.     {
  734.       D_RELNUM (result, FILE2, i)
  735.         = D_RELNUM (result, FILEC, current0line);
  736.       D_RELLEN (result, FILE2, i)
  737.         = D_RELLEN (result, FILEC, current0line++);
  738.     }
  739.     }
  740.  
  741.   /* Set correspond */
  742.   if (!using[0])
  743.     D3_TYPE (result) = DIFF_3RD;
  744.   else if (!using[1])
  745.     D3_TYPE (result) = DIFF_2ND;
  746.   else
  747.     {
  748.       int nl1
  749.     = D_HIGHLINE (result, FILE1) - D_LOWLINE (result, FILE1) + 1;
  750.       int nl2
  751.     = D_HIGHLINE (result, FILE2) - D_LOWLINE (result, FILE2) + 1;
  752.  
  753.       if (nl1 != nl2
  754.       || !compare_line_list (D_LINEARRAY (result, FILE1),
  755.                  D_LENARRAY (result, FILE1),
  756.                  D_LINEARRAY (result, FILE2),
  757.                  D_LENARRAY (result, FILE2),
  758.                  nl1))
  759.     D3_TYPE (result) = DIFF_ALL;
  760.       else
  761.     D3_TYPE (result) = DIFF_1ST;
  762.     }
  763.   
  764.   return result;
  765. }
  766.  
  767. /*
  768.  * This routine copies pointers from a list of strings to a different list
  769.  * of strings.  If a spot in the second list is already filled, it
  770.  * makes sure that it is filled with the same string; if not it
  771.  * returns 0, the copy incomplete.
  772.  * Upon successful completion of the copy, it returns 1.
  773.  */
  774. int
  775. copy_stringlist (fromptrs, fromlengths, toptrs, tolengths, copynum)
  776.      char *fromptrs[], *toptrs[];
  777.      int *fromlengths, *tolengths;
  778.      int copynum;
  779. {
  780.   register char
  781.     **f = fromptrs,
  782.     **t = toptrs;
  783.   register int
  784.     *fl = fromlengths,
  785.     *tl = tolengths;
  786.   
  787.   while (copynum--)
  788.     {
  789.       if (*t)
  790.     { 
  791.       if (*fl != *tl || bcmp (*f, *t, *fl))
  792.          return 0;
  793.      }
  794.       else
  795.     { *t = *f ; *tl = *fl; }
  796.  
  797.       t++; f++; tl++; fl++;
  798.     }
  799.   return 1;
  800. }
  801.  
  802. /*
  803.  * Create a diff3_block, with ranges as specified in the arguments.
  804.  * Allocate the arrays for the various pointers (and zero them) based
  805.  * on the arguments passed.  Return the block as a result.
  806.  */
  807. struct diff3_block *
  808. create_diff3_block (low0, high0, low1, high1, low2, high2)
  809.      register int low0, high0, low1, high1, low2, high2;
  810. {
  811.   struct diff3_block *result = ALLOCATE (1, struct diff3_block);
  812.   int numlines;
  813.  
  814.   D3_TYPE (result) = ERROR;
  815.  
  816.   /* Assign ranges */
  817.   D_LOWLINE (result, FILE0) = low0;
  818.   D_HIGHLINE (result, FILE0) = high0;
  819.   D_LOWLINE (result, FILE1) = low1;
  820.   D_HIGHLINE (result, FILE1) = high1;
  821.   D_LOWLINE (result, FILE2) = low2;
  822.   D_HIGHLINE (result, FILE2) = high2;
  823.  
  824.   /* Allocate and zero space */
  825.   numlines = D_NUMLINES (result, FILE0);
  826.   if (numlines)
  827.     {
  828.       D_LINEARRAY (result, FILE0) = ALLOCATE (numlines, char *);
  829.       D_LENARRAY (result, FILE0) = ALLOCATE (numlines, int);
  830.       bzero (D_LINEARRAY (result, FILE0), (numlines * sizeof (char *)));
  831.       bzero (D_LENARRAY (result, FILE0), (numlines * sizeof (int)));
  832.     }
  833.   else
  834.     {
  835.       D_LINEARRAY (result, FILE0) = (char **) 0;
  836.       D_LENARRAY (result, FILE0) = (int *) 0;
  837.     }
  838.  
  839.   numlines = D_NUMLINES (result, FILE1);
  840.   if (numlines)
  841.     {
  842.       D_LINEARRAY (result, FILE1) = ALLOCATE (numlines, char *);
  843.       D_LENARRAY (result, FILE1) = ALLOCATE (numlines, int);
  844.       bzero (D_LINEARRAY (result, FILE1), (numlines * sizeof (char *)));
  845.       bzero (D_LENARRAY (result, FILE1), (numlines * sizeof (int)));
  846.     }
  847.   else
  848.     {
  849.       D_LINEARRAY (result, FILE1) = (char **) 0;
  850.       D_LENARRAY (result, FILE1) = (int *) 0;
  851.     }
  852.  
  853.   numlines = D_NUMLINES (result, FILE2);
  854.   if (numlines)
  855.     {
  856.       D_LINEARRAY (result, FILE2) = ALLOCATE (numlines, char *);
  857.       D_LENARRAY (result, FILE2) = ALLOCATE (numlines, int);
  858.       bzero (D_LINEARRAY (result, FILE2), (numlines * sizeof (char *)));
  859.       bzero (D_LENARRAY (result, FILE2), (numlines * sizeof (int)));
  860.     }
  861.   else
  862.     {
  863.       D_LINEARRAY (result, FILE2) = (char **) 0;
  864.       D_LENARRAY (result, FILE2) = (int *) 0;
  865.     }
  866.  
  867.   /* Return */
  868.   return result;
  869. }
  870.  
  871. /*
  872.  * Compare two lists of lines of text.
  873.  * Return 1 if they are equivalent, 0 if not.
  874.  */
  875. int
  876. compare_line_list (list1, lengths1, list2, lengths2, nl)
  877.      char *list1[], *list2[];
  878.      int *lengths1, *lengths2;
  879.      int nl;
  880. {
  881.   char
  882.     **l1 = list1,
  883.     **l2 = list2;
  884.   int
  885.     *lgths1 = lengths1,
  886.     *lgths2 = lengths2;
  887.   
  888.   while (nl--)
  889.     if (!*l1 || !*l2 || *lgths1 != *lgths2++
  890.     || bcmp (*l1++, *l2++, *lgths1++))
  891.       return 0;
  892.   return 1;
  893. }
  894.  
  895. /* 
  896.  * Routines to input and parse two way diffs.
  897.  */
  898.  
  899. extern char *environ;        /* I hope this is here */
  900.  
  901. #define    DIFF_CHUNK_SIZE    10000
  902.  
  903. struct diff_block *
  904. process_diff (filea, fileb)
  905.      char *filea, *fileb;
  906. {
  907.   char *diff_contents;
  908.   int diff_size;
  909.   char *scan_diff;
  910.   enum diff_type dt;
  911.   int i;
  912.   struct diff_block *block_list, *block_list_end, *bptr;
  913.  
  914.   diff_size = read_diff (filea, fileb, &diff_contents);
  915.   scan_diff = diff_contents;
  916.   bptr = block_list_end = block_list = (struct diff_block *) 0;
  917.  
  918.   while (scan_diff - diff_contents < diff_size)
  919.     {
  920.       bptr = ALLOCATE (1, struct diff_block);
  921.       bptr->lines[0] = bptr->lines[1] = (char **) 0;
  922.       bptr->lengths[0] = bptr->lengths[1] = (int *) 0;
  923.       
  924.       dt = process_diff_control (&scan_diff, bptr);
  925.       if (dt == ERROR) fatal ("Bad format in diff output");
  926.       if (*scan_diff != '\n') fatal ("Bad format in diff output");
  927.       scan_diff++;
  928.       
  929.       /* Force appropriate ranges to be null, if necessary */
  930.       switch (dt)
  931.     {
  932.     case ADD:
  933.       bptr->ranges[0][0]++;
  934.       break;
  935.     case DELETE:
  936.       bptr->ranges[1][0]++;
  937.       break;
  938.     case CHANGE:
  939.       break;
  940.     default:
  941.       fatal ("internal: Bad diff type in process_diff");
  942.       break;
  943.     }
  944.       
  945.       /* Allocate space for the pointers for the lines from filea, and
  946.      parcel them out among these pointers */
  947.       if (dt != ADD)
  948.     {
  949.       bptr->lines[0] = ALLOCATE ((bptr->ranges[0][END]
  950.                       - bptr->ranges[0][START] + 1),
  951.                      char *);
  952.       bptr->lengths[0] = ALLOCATE ((bptr->ranges[0][END]
  953.                     - bptr->ranges[0][START] + 1),
  954.                        int);
  955.       for (i = 0; i <= (bptr->ranges[0][END]
  956.                 - bptr->ranges[0][START]); i++)
  957.         scan_diff = scan_diff_line (scan_diff,
  958.                     &(bptr->lines[0][i]),
  959.                     &(bptr->lengths[0][i]),
  960.                     diff_contents + diff_size,
  961.                     '<');
  962.     }
  963.       
  964.       /* Get past the separator for changes */
  965.       if (dt == CHANGE)
  966.     {
  967.       if (strncmp (scan_diff, "---\n", 4))
  968.         fatal ("Bad diff format: bad change separator");
  969.       scan_diff += 4;
  970.     }
  971.       
  972.       /* Allocate space for the pointers for the lines from fileb, and
  973.      parcel them out among these pointers */
  974.       if (dt != DELETE)
  975.     {
  976.       bptr->lines[1] = ALLOCATE ((bptr->ranges[1][END]
  977.                       - bptr->ranges[1][START] + 1),
  978.                      char *);
  979.       bptr->lengths[1] = ALLOCATE ((bptr->ranges[1][END]
  980.                     - bptr->ranges[1][START] + 1),
  981.                        int);
  982.       for (i = 0; i <= (bptr->ranges[1][END]
  983.                 - bptr->ranges[1][START]); i++)
  984.         scan_diff = scan_diff_line (scan_diff,
  985.                     &(bptr->lines[1][i]),
  986.                     &(bptr->lengths[1][i]),
  987.                     diff_contents + diff_size,
  988.                     '>');
  989.     }
  990.       
  991.       /* Place this block on the blocklist */
  992.       if (block_list_end)
  993.     block_list_end->next = bptr;
  994.       else
  995.     block_list = bptr;
  996.       
  997.       block_list_end = bptr;
  998.       
  999.     }
  1000.  
  1001.   if (scan_diff - diff_contents != diff_size)
  1002.     fatal ("bad diff format; incomplete last line");
  1003.  
  1004.   return block_list;
  1005. }
  1006.  
  1007. /*
  1008.  * This routine will parse a normal format diff control string.  It
  1009.  * returns the type of the diff (ERROR if the format is bad).  All of
  1010.  * the other important information is filled into to the structure
  1011.  * pointed to by db, and the string pointer (whose location is passed
  1012.  * to this routine) is updated to point beyond the end of the string
  1013.  * parsed.  Note that only the ranges in the diff_block will be set by
  1014.  * this routine.
  1015.  *
  1016.  * If some specific pair of numbers has been reduced to a single
  1017.  * number, then both corresponding numbers in the diff block are set
  1018.  * to that number.  In general these numbers are interpetted as ranges
  1019.  * inclusive, unless being used by the ADD or DELETE commands.  It is
  1020.  * assumed that these will be special cased in a superior routine.  
  1021.  */
  1022.  
  1023. enum diff_type
  1024. process_diff_control (string, db)
  1025.      char **string;
  1026.      struct diff_block *db;
  1027. {
  1028.   char *s = *string;
  1029.   int holdnum;
  1030.   enum diff_type type;
  1031.  
  1032. /* These macros are defined here because they can use variables
  1033.    defined in this function.  Don't try this at home kids, we're
  1034.    trained professionals!
  1035.  
  1036.    Also note that SKIPWHITE only recognizes tabs and spaces, and
  1037.    that READNUM can only read positive, integral numbers */
  1038.  
  1039. #define    SKIPWHITE(s)    { while (*s == ' ' || *s == '\t') s++; }
  1040. #define    READNUM(s, num)    \
  1041.     { if (!isdigit (*s)) return ERROR; holdnum = 0;    \
  1042.       do { holdnum = (*s++ - '0' + holdnum * 10); }    \
  1043.       while (isdigit (*s)); (num) = holdnum; }
  1044.  
  1045.   /* Read first set of digits */
  1046.   SKIPWHITE (s);
  1047.   READNUM (s, db->ranges[0][START]);
  1048.  
  1049.   /* Was that the only digit? */
  1050.   SKIPWHITE(s);
  1051.   if (*s == ',')
  1052.     {
  1053.       /* Get the next digit */
  1054.       s++;
  1055.       READNUM (s, db->ranges[0][END]);
  1056.     }
  1057.   else
  1058.     db->ranges[0][END] = db->ranges[0][START];
  1059.  
  1060.   /* Get the letter */
  1061.   SKIPWHITE (s);
  1062.   switch (*s)
  1063.     {
  1064.     case 'a':
  1065.       type = ADD;
  1066.       break;
  1067.     case 'c':
  1068.       type = CHANGE;
  1069.       break;
  1070.     case 'd':
  1071.       type = DELETE;
  1072.       break;
  1073.     default:
  1074.       return ERROR;            /* Bad format */
  1075.     }
  1076.   s++;                /* Past letter */
  1077.   
  1078.   /* Read second set of digits */
  1079.   SKIPWHITE (s);
  1080.   READNUM (s, db->ranges[1][START]);
  1081.  
  1082.   /* Was that the only digit? */
  1083.   SKIPWHITE(s);
  1084.   if (*s == ',')
  1085.     {
  1086.       /* Get the next digit */
  1087.       s++;
  1088.       READNUM (s, db->ranges[1][END]);
  1089.       SKIPWHITE (s);        /* To move to end */
  1090.     }
  1091.   else
  1092.     db->ranges[1][END] = db->ranges[1][START];
  1093.  
  1094.   *string = s;
  1095.   return type;
  1096. }
  1097.  
  1098. int
  1099. read_diff (filea, fileb, output_placement)
  1100.      char *filea, *fileb;
  1101.      char **output_placement;
  1102. {
  1103.   char *cmd;
  1104.   void    *malloc();
  1105.   int pipefd;
  1106.   FILE *pipefp, *popenl();
  1107.   char *diff_result;
  1108.   long current_chunk_size;
  1109.   int bytes;
  1110.   int total;
  1111.  
  1112.   cmd = (char *)malloc(strlen(diff_program) + strlen(filea) + strlen(fileb) + 2
  1113. ;
  1114.   if (cmd == NULL) {
  1115.       printf("Couldn't obtain memory for diff command\n");
  1116.       exit(1);
  1117.       }
  1118.  
  1119.   pipefp = popenl(diff_program, filea, fileb, NULL, "r");
  1120.   if (pipefp == NULL) {
  1121.       printf("Couldn't open pipe to diff program\n");
  1122.       exit(1);
  1123.       }
  1124.   pipefd = fileno(pipefp); 
  1125.   current_chunk_size = DIFF_CHUNK_SIZE;
  1126.   diff_result = (char *) xmalloc (current_chunk_size);
  1127.   total = 0;
  1128.   do {
  1129.     bytes = myread (pipefd,
  1130.             diff_result + total,
  1131.             current_chunk_size - total);
  1132.     total += bytes;
  1133.     if (total == current_chunk_size)
  1134.       diff_result = (char *) xrealloc (diff_result, (current_chunk_size *= 2));
  1135.   } while (bytes);
  1136.  
  1137.   *output_placement = diff_result;
  1138.   pclose(pipefp);
  1139.   return total;
  1140. }
  1141.  
  1142.  
  1143. /*
  1144.  * Scan a regular diff line (consisting of > or <, followed by a
  1145.  * space, followed by text (including nulls) up to a newline.
  1146.  *
  1147.  * This next routine began life as a macro and many parameters in it
  1148.  * are used as call-by-reference values.
  1149.  */
  1150. char *
  1151. scan_diff_line (scan_ptr, set_start, set_length, limit, firstchar)
  1152.      char *scan_ptr, **set_start;
  1153.      int *set_length;
  1154.      char *limit;
  1155.      char firstchar;
  1156. {
  1157.   char *line_ptr = scan_ptr + 2;
  1158.  
  1159.   if (!(scan_ptr[0] == (firstchar)
  1160.     && scan_ptr[1] == ' '))
  1161.     fatal ("Bad diff format; incorrect leading line chars");
  1162.  
  1163.   *set_start = line_ptr;
  1164.   while (*line_ptr != '\n') line_ptr++;
  1165.   
  1166.   if (line_ptr >= limit)
  1167.     fatal ("Bad diff format; overflow in parse");
  1168.  
  1169.   /* Don't include newline, but do return the beginning of the
  1170.      next line */
  1171.   *set_length = line_ptr - *set_start;
  1172.  
  1173.   return line_ptr + 1;
  1174. }
  1175.  
  1176. /*
  1177.  * This routine outputs a three way diff passed as a list of
  1178.  * diff3_block's.
  1179.  * The argument MAPPING is indexed by external file number (in the
  1180.  * argument list) and contains the internal file number (from the
  1181.  * diff passed).  This is important because the user expects his
  1182.  * outputs in terms of the argument list number, and the diff passed
  1183.  * may have been done slightly differently (if the first argument in
  1184.  * the argument list was the standard input, for example).
  1185.  */
  1186. void
  1187. output_diff3 (outputfile, diff, mapping)
  1188.      FILE *outputfile;
  1189.      struct diff3_block *diff;
  1190.      int mapping[3];
  1191. {
  1192.   int rev_mapping[3];
  1193.   static int eliminate[3] = { 1, 0, 0};
  1194.   int i;
  1195.   int oddoneout;
  1196.   char *cp;
  1197.   struct diff3_block *ptr;
  1198.   int line;
  1199.   int dontprint;
  1200.   static int skew_increment[3] = { 2, 3, 1 }; /* 0==>2==>1==>3 */
  1201.  
  1202.   for (i = 0; i < 3; i++)
  1203.     rev_mapping [mapping[i]] = i;
  1204.  
  1205.   for (ptr = diff; ptr; ptr = D_NEXT (ptr))
  1206.     {
  1207.       char x[2];
  1208.  
  1209.       switch (ptr->correspond)
  1210.     {
  1211.     case DIFF_ALL:
  1212.       x[0] = '\0';
  1213.       dontprint = 3;    /* Print them all */
  1214.       oddoneout = 3;    /* Nobody's odder than anyone else */
  1215.       break;
  1216.     case DIFF_1ST:
  1217.     case DIFF_2ND:
  1218.     case DIFF_3RD:
  1219.       oddoneout = rev_mapping[(int) ptr->correspond - (int) DIFF_1ST];
  1220.         
  1221.       x[0] = oddoneout + '1';
  1222.       x[1] = '\0';
  1223.       dontprint = eliminate [oddoneout];
  1224.       break;
  1225.     default:
  1226.       fatal ("internal: Bad diff type passed to output");
  1227.     }
  1228.       fprintf (outputfile, "====%s\n", x);
  1229.  
  1230.       /* Go 0, 2, 1 if the first and third outputs are equivalent. */
  1231.       for (i = 0; i < 3;
  1232.        i = (oddoneout == 1 ? skew_increment[i] : i + 1))
  1233.     {
  1234.       int realfile = mapping[i];
  1235.       int
  1236.         lowt = D_LOWLINE (ptr, realfile),
  1237.         hight = D_HIGHLINE (ptr, realfile);
  1238.       
  1239.       fprintf (outputfile, "%d:", i + 1);
  1240.       switch (lowt - hight)
  1241.         {
  1242.         case 1:
  1243.           fprintf (outputfile, "%da\n", lowt - 1);
  1244.           break;
  1245.         case 0:
  1246.           fprintf (outputfile, "%dc\n", lowt);
  1247.           break;
  1248.         default:
  1249.           fprintf (outputfile, "%d,%dc\n", lowt, hight);
  1250.           break;
  1251.         }
  1252.  
  1253.       if (i == dontprint) continue;
  1254.  
  1255.       for (line = 0; line < hight - lowt + 1; line++)
  1256.         {
  1257.           fprintf (outputfile, "  ");
  1258.           for (cp = D_RELNUM (ptr, realfile, line);
  1259.            cp < (D_RELNUM (ptr, realfile, line)
  1260.              + D_RELLEN (ptr, realfile, line));
  1261.            cp++)
  1262.         putc (*cp, outputfile);
  1263.           putc ('\n', outputfile);
  1264.         }
  1265.     }
  1266.     }
  1267. }
  1268.  
  1269. /*
  1270.  * This routine outputs a diff3 set of blocks as an ed script.  This
  1271.  * script applies the changes between file's 2 & 3 to file 1.  It
  1272.  * takes the precise format of the ed script to be output from global
  1273.  * variables set during options processing.  Note that it does
  1274.  * destructive things to the set of diff3 blocks it is passed; it
  1275.  * reverses their order (this gets around the problems involved with
  1276.  * changing line numbers in an ed script).
  1277.  *
  1278.  * Note that this routine has the same problem of mapping as the last
  1279.  * one did; the variable MAPPING maps from file number according to
  1280.  * the argument list to file number according to the diff passed.  All
  1281.  * files listed below are in terms of the argument list.
  1282.  *
  1283.  * Also, occasionally this routine needs the real names of the files
  1284.  * on which it works.  Thus file0, file1, and file2 are the filenames
  1285.  * passed on the command line.
  1286.  *
  1287.  * See options.h for documentation on the global variables which this
  1288.  * routine pays attention to.
  1289.  */
  1290. void
  1291. output_diff3_edscript (outputfile, diff, mapping, file0, file1, file2)
  1292.      FILE *outputfile;
  1293.      struct diff3_block *diff;
  1294.      int mapping[3];
  1295.      char *file0, *file1, *file2;
  1296. {
  1297.   int rev_mapping[3];
  1298.   int i;
  1299.   int leading_dot;
  1300.   struct diff3_block *newblock, *thisblock;
  1301.   char *cp;
  1302.  
  1303.   leading_dot = 0;
  1304.  
  1305.   for (i = 0; i < 3; i++)
  1306.     rev_mapping [mapping [i]] = i;
  1307.  
  1308.   newblock = reverse_diff3_blocklist (diff);
  1309.  
  1310.   for (thisblock = newblock; thisblock; thisblock = thisblock->next)
  1311.     {
  1312.       /* Must do mapping correctly.  */
  1313.       enum diff_type type
  1314.     = ((thisblock->correspond == DIFF_ALL) ?
  1315.        DIFF_ALL :
  1316.        ((enum diff_type)
  1317.         (((int) DIFF_1ST)
  1318.          + rev_mapping [(int) thisblock->correspond - (int) DIFF_1ST])));
  1319.  
  1320.       /* If we aren't supposed to do this output block, skip it */
  1321.       if (type == DIFF_2ND || type == DIFF_1ST
  1322.       || (type == DIFF_3RD && dont_write_simple)
  1323.       || (type == DIFF_ALL && dont_write_overlap))
  1324.     continue;
  1325.  
  1326.       if (flagging && type == DIFF_ALL)
  1327.     /* Do special flagging */
  1328.     {
  1329.       overlaps++; 
  1330.       /* Put in lines from FILE2 with bracket */
  1331.       fprintf (outputfile, "%da\n",
  1332.            D_HIGHLINE (thisblock, mapping [FILE0]));
  1333.       fprintf (outputfile, "=======\n");
  1334.       for (i = 0;
  1335.            i < D_NUMLINES (thisblock, mapping [FILE2]);
  1336.            i++)
  1337.         {
  1338.           if (D_RELNUM (thisblock, mapping[FILE2], i)[0] == '.')
  1339.         { leading_dot = 1; fprintf(outputfile, "."); }
  1340.           for (cp = D_RELNUM (thisblock, mapping [FILE2], i);
  1341.            cp < (D_RELNUM (thisblock, mapping [FILE2], i)
  1342.              + D_RELLEN (thisblock, mapping [FILE2], i));
  1343.            cp++)
  1344.         putc (*cp, outputfile);
  1345.           putc ('\n', outputfile);
  1346.         }
  1347.       fprintf (outputfile, ">>>>>>> %s\n.\n", file2);
  1348.  
  1349.       /* Add in code to take care of leading dots, if necessary. */
  1350.       if (leading_dot)
  1351.         {
  1352.           fprintf (outputfile, "%d,%ds/^\\.\\./\\./\n",
  1353.                D_HIGHLINE (thisblock, mapping [FILE0]) + 1,
  1354.                (D_HIGHLINE (thisblock, mapping [FILE0])
  1355.             + D_NUMLINES (thisblock, mapping [FILE2])));
  1356.           leading_dot = 0;
  1357.         }
  1358.  
  1359.       /* Put in code to do initial bracket of lines from FILE0  */
  1360.       fprintf (outputfile, "%da\n<<<<<<< %s\n.\n",
  1361.            D_LOWLINE (thisblock, mapping[FILE0]) - 1,
  1362.            file0);
  1363.     }
  1364.       else if (D_NUMLINES (thisblock, mapping [FILE2]) == 0)
  1365.     /* Write out a delete */
  1366.     {
  1367.       if (D_NUMLINES (thisblock, mapping [FILE0]) == 1)
  1368.         fprintf (outputfile, "%dd\n",
  1369.              D_LOWLINE (thisblock, mapping [FILE0]));
  1370.       else
  1371.         fprintf (outputfile, "%d,%dd\n",
  1372.              D_LOWLINE (thisblock, mapping [FILE0]),
  1373.              D_HIGHLINE (thisblock, mapping [FILE0]));
  1374.     }
  1375.       else
  1376.     /* Write out an add or change */
  1377.     {
  1378.       switch (D_NUMLINES (thisblock, mapping [FILE0]))
  1379.         {
  1380.         case 0:
  1381.           fprintf (outputfile, "%da\n",
  1382.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1383.           break;
  1384.         case 1:
  1385.           fprintf (outputfile, "%dc\n",
  1386.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1387.           break;
  1388.         default:
  1389.           fprintf (outputfile, "%d,%dc\n",
  1390.                D_LOWLINE (thisblock, mapping [FILE0]),
  1391.                D_HIGHLINE (thisblock, mapping [FILE0]));
  1392.           break;
  1393.         }
  1394.       for (i = 0;
  1395.            i < D_NUMLINES (thisblock, mapping [FILE2]);
  1396.            i++)
  1397.         {
  1398.           if (D_RELNUM (thisblock, mapping [FILE2], i)[0] == '.')
  1399.         { leading_dot = 1; fprintf (outputfile, "."); }
  1400.           for (cp = D_RELNUM (thisblock, mapping [FILE2], i);
  1401.            cp < (D_RELNUM (thisblock, mapping [FILE2], i)
  1402.              + D_RELLEN (thisblock, mapping [FILE2], i));
  1403.            cp++)
  1404.         putc (*cp, outputfile);
  1405.           putc ('\n', outputfile);
  1406.         }
  1407.       fprintf (outputfile, ".\n");
  1408.       
  1409.       /* Add in code to take care of leading dots, if necessary. */
  1410.       if (leading_dot)
  1411.         {
  1412.           fprintf (outputfile, "%d,%ds/^\\.\\./\\./\n",
  1413.                D_HIGHLINE (thisblock, mapping [FILE0]) + 1,
  1414.                (D_HIGHLINE (thisblock, mapping [FILE0])
  1415.             + D_NUMLINES (thisblock, mapping [FILE2])));
  1416.           leading_dot = 0;
  1417.         }
  1418.     }
  1419.     }
  1420.   if (finalwrite) fprintf (outputfile, "w\nq\n");
  1421. }
  1422.  
  1423. /*
  1424.  * Reverse the order of the list of diff3 blocks.
  1425.  */
  1426. struct diff3_block *
  1427. reverse_diff3_blocklist (diff)
  1428.      struct diff3_block *diff;
  1429. {
  1430.   register struct diff3_block *tmp, *next, *prev;
  1431.  
  1432.   for (tmp = diff, prev = (struct diff3_block *) 0;
  1433.        tmp; tmp = next)
  1434.     {
  1435.       next = tmp->next;
  1436.       tmp->next = prev;
  1437.       prev = tmp;
  1438.     }
  1439.   
  1440.   return prev;
  1441. }
  1442.  
  1443. int
  1444. myread (fd, ptr, size)
  1445.      int fd, size;
  1446.      char *ptr;
  1447. {
  1448.   int result = read (fd, ptr, size);
  1449.   if (result < 0)
  1450.     perror_with_exit ("Read failed");
  1451.   return result;
  1452. }
  1453.  
  1454. void *
  1455. xmalloc (size)
  1456.      int size;
  1457. {
  1458.   void *result = (void *) calloc (1,size + 100);
  1459.   if (!result)
  1460.     fatal ("Malloc failed");
  1461.   return result;
  1462. }
  1463.  
  1464. void *
  1465. xrealloc (ptr, size)
  1466.      void *ptr;
  1467.      int size;
  1468. {
  1469.   void *result = (void *) realloc (ptr, size);
  1470.   if (!result)
  1471.     fatal ("Realloc failed\n");
  1472.   return result;
  1473. }
  1474.  
  1475. void fatal (string)
  1476.      char *string;
  1477. {
  1478.   printf("%s: %s\n",argv0, string);
  1479.   exit (1);
  1480. }
  1481. void perror_with_exit (string)
  1482.      char *string;
  1483. {
  1484.   perror (string);
  1485.   exit (1);
  1486. }
  1487.