home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / rcs567s.zip / diff16 / analyze.c < prev    next >
C/C++ Source or Header  |  1994-06-25  |  30KB  |  1,014 lines

  1. /* Analyze file differences for GNU DIFF.
  2.    Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  3.    Modified for DOS and OS/2 on 1991/09/14 by Kai Uwe Rommel
  4.     <rommel@ars.muc.de>.
  5.  
  6. This file is part of GNU DIFF.
  7.  
  8. GNU DIFF is free software; you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation; either version 1, or (at your option)
  11. any later version.
  12.  
  13. GNU DIFF is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. GNU General Public License for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with GNU DIFF; see the file COPYING.  If not, write to
  20. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* The basic algorithm is described in: 
  23.    "An O(ND) Difference Algorithm and its Variations", Eugene Myers,
  24.    Algorithmica Vol. 1 No. 2, 1986, p 251.  */
  25.  
  26. #include "diff.h"
  27.  
  28. struct change *find_change ();
  29. void finish_output ();
  30. void print_context_header ();
  31. void print_context_script ();
  32. void print_ed_script ();
  33. void print_ifdef_script ();
  34. void print_normal_script ();
  35. void print_rcs_script ();
  36. void pr_forward_ed_script ();
  37. void print_merged_script ();
  38. void setup_output ();
  39.  
  40. extern int no_discards;
  41.  
  42. static int *xvec, *yvec;    /* Vectors being compared. */
  43. #ifdef MSDOS
  44. static int huge *fdiag;
  45. static int huge *bdiag;
  46. #else
  47. static int *fdiag;        /* Vector, indexed by diagonal, containing
  48.                    the X coordinate of the point furthest
  49.                    along the given diagonal in the forward
  50.                    search of the edit matrix. */
  51. static int *bdiag;        /* Vector, indexed by diagonal, containing
  52.                    the X coordinate of the point furthest
  53.                    along the given diagonal in the backward
  54.                    search of the edit matrix. */
  55. #endif
  56.  
  57. /* Find the midpoint of the shortest edit script for a specified
  58.    portion of the two files.
  59.  
  60.    We scan from the beginnings of the files, and simultaneously from the ends,
  61.    doing a breadth-first search through the space of edit-sequence.
  62.    When the two searches meet, we have found the midpoint of the shortest
  63.    edit sequence.
  64.  
  65.    The value returned is the number of the diagonal on which the midpoint lies.
  66.    The diagonal number equals the number of inserted lines minus the number
  67.    of deleted lines (counting only lines before the midpoint).
  68.    The edit cost is stored into *COST; this is the total number of
  69.    lines inserted or deleted (counting only lines before the midpoint).
  70.  
  71.    This function assumes that the first lines of the specified portions
  72.    of the two files do not match, and likewise that the last lines do not
  73.    match.  The caller must trim matching lines from the beginning and end
  74.    of the portions it is going to specify.
  75.  
  76.    Note that if we return the "wrong" diagonal value, or if
  77.    the value of bdiag at that diagonal is "wrong",
  78.    the worst this can do is cause suboptimal diff output.
  79.    It cannot cause incorrect diff output.  */
  80.  
  81. static int
  82. diag (xoff, xlim, yoff, ylim, cost)
  83.      int xoff, xlim, yoff, ylim;
  84.      int *cost;
  85. {
  86. #ifdef MSDOS
  87.   int huge *const fd = fdiag;
  88.   int huge *const bd = bdiag;
  89.   int huge *const xv = xvec;
  90.   int huge *const yv = yvec;
  91. #else
  92.   int *const fd = fdiag;    /* Give the compiler a chance. */
  93.   int *const bd = bdiag;    /* Additional help for the compiler. */
  94.   int *const xv = xvec;        /* Still more help for the compiler. */
  95.   int *const yv = yvec;        /* And more and more . . . */
  96. #endif
  97.   const int dmin = xoff - ylim;    /* Minimum valid diagonal. */
  98.   const int dmax = xlim - yoff;    /* Maximum valid diagonal. */
  99.   const int fmid = xoff - yoff;    /* Center diagonal of top-down search. */
  100.   const int bmid = xlim - ylim;    /* Center diagonal of bottom-up search. */
  101.   int fmin = fmid, fmax = fmid;    /* Limits of top-down search. */
  102.   int bmin = bmid, bmax = bmid;    /* Limits of bottom-up search. */
  103.   int c;            /* Cost. */
  104.   int odd = fmid - bmid & 1;    /* True if southeast corner is on an odd
  105.                    diagonal with respect to the northwest. */
  106.  
  107.   fd[fmid] = xoff;
  108.   bd[bmid] = xlim;
  109.  
  110.   for (c = 1;; ++c)
  111.     {
  112.       int d;            /* Active diagonal. */
  113.       int big_snake = 0;
  114.  
  115.       /* Extend the top-down search by an edit step in each diagonal. */
  116.       fmin > dmin ? fd[--fmin - 1] = -1 : ++fmin;
  117.       fmax < dmax ? fd[++fmax + 1] = -1 : --fmax;
  118.       for (d = fmax; d >= fmin; d -= 2)
  119.     {
  120.       int x, y, oldx, tlo = fd[d - 1], thi = fd[d + 1];
  121.  
  122.       if (tlo >= thi)
  123.         x = tlo + 1;
  124.       else
  125.         x = thi;
  126.       oldx = x;
  127.       y = x - d;
  128.       while (x < xlim && y < ylim && xv[x] == yv[y])
  129.         ++x, ++y;
  130.       if (x - oldx > 20)
  131.         big_snake = 1;
  132.       fd[d] = x;
  133.       if (odd && bmin <= d && d <= bmax && bd[d] <= fd[d])
  134.         {
  135.           *cost = 2 * c - 1;
  136.           return d;
  137.         }
  138.     }
  139.  
  140.       /* Similar extend the bottom-up search. */
  141.       bmin > dmin ? bd[--bmin - 1] = INT_MAX : ++bmin;
  142.       bmax < dmax ? bd[++bmax + 1] = INT_MAX : --bmax;
  143.       for (d = bmax; d >= bmin; d -= 2)
  144.     {
  145.       int x, y, oldx, tlo = bd[d - 1], thi = bd[d + 1];
  146.  
  147.       if (tlo < thi)
  148.         x = tlo;
  149.       else
  150.         x = thi - 1;
  151.       oldx = x;
  152.       y = x - d;
  153.       while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1])
  154.         --x, --y;
  155.       if (oldx - x > 20)
  156.         big_snake = 1;
  157.       bd[d] = x;
  158.       if (!odd && fmin <= d && d <= fmax && bd[d] <= fd[d])
  159.         {
  160.           *cost = 2 * c;
  161.           return d;
  162.         }
  163.     }
  164.  
  165.       /* Heuristic: check occasionally for a diagonal that has made
  166.      lots of progress compared with the edit distance.
  167.      If we have any such, find the one that has made the most
  168.      progress and return it as if it had succeeded.
  169.  
  170.      With this heuristic, for files with a constant small density
  171.      of changes, the algorithm is linear in the file size.  */
  172.  
  173.       if (c > 200 && big_snake && heuristic)
  174.     {
  175.       int best;
  176.       int bestpos;
  177.  
  178.       best = 0;
  179.       for (d = fmax; d >= fmin; d -= 2)
  180.         {
  181.           int dd = d - fmid;
  182.           if ((fd[d] - xoff)*2 - dd > 12 * (c + (dd > 0 ? dd : -dd)))
  183.         {
  184.           if (fd[d] * 2 - dd > best
  185.               && fd[d] - xoff > 20
  186.               && fd[d] - d - yoff > 20)
  187.             {
  188.               int k;
  189.               int x = fd[d];
  190.  
  191.               /* We have a good enough best diagonal;
  192.              now insist that it end with a significant snake.  */
  193.               for (k = 1; k <= 20; k++)
  194.             if (xvec[x - k] != yvec[x - d - k])
  195.               break;
  196.  
  197.               if (k == 21)
  198.             {
  199.               best = fd[d] * 2 - dd;
  200.               bestpos = d;
  201.             }
  202.             }
  203.         }
  204.         }
  205.       if (best > 0)
  206.         {
  207.           *cost = 2 * c - 1;
  208.           return bestpos;
  209.         }
  210.  
  211.       best = 0;
  212.       for (d = bmax; d >= bmin; d -= 2)
  213.         {
  214.           int dd = d - bmid;
  215.           if ((xlim - bd[d])*2 + dd > 12 * (c + (dd > 0 ? dd : -dd)))
  216.         {
  217.           if ((xlim - bd[d]) * 2 + dd > best
  218.               && xlim - bd[d] > 20
  219.               && ylim - (bd[d] - d) > 20)
  220.             {
  221.               /* We have a good enough best diagonal;
  222.              now insist that it end with a significant snake.  */
  223.               int k;
  224.               int x = bd[d];
  225.  
  226.               for (k = 0; k < 20; k++)
  227.             if (xvec[x + k] != yvec[x - d + k])
  228.               break;
  229.               if (k == 20)
  230.             {
  231.               best = (xlim - bd[d]) * 2 + dd;
  232.               bestpos = d;
  233.             }
  234.             }
  235.         }
  236.         }
  237.       if (best > 0)
  238.         {
  239.           *cost = 2 * c - 1;
  240.           return bestpos;
  241.         }
  242.     }
  243.     }
  244. }
  245.  
  246. /* Compare in detail contiguous subsequences of the two files
  247.    which are known, as a whole, to match each other.
  248.  
  249.    The results are recorded in the vectors files[N].changed_flag, by
  250.    storing a 1 in the element for each line that is an insertion or deletion.
  251.  
  252.    The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
  253.  
  254.    Note that XLIM, YLIM are exclusive bounds.
  255.    All line numbers are origin-0 and discarded lines are not counted.  */
  256.  
  257. static void
  258. compareseq (xoff, xlim, yoff, ylim)
  259.      int xoff, xlim, yoff, ylim;
  260. {
  261.   /* Slide down the bottom initial diagonal. */
  262.   while (xoff < xlim && yoff < ylim && xvec[xoff] == yvec[yoff])
  263.     ++xoff, ++yoff;
  264.   /* Slide up the top initial diagonal. */
  265.   while (xlim > xoff && ylim > yoff && xvec[xlim - 1] == yvec[ylim - 1])
  266.     --xlim, --ylim;
  267.   
  268.   /* Handle simple cases. */
  269.   if (xoff == xlim)
  270.     while (yoff < ylim)
  271.       files[1].changed_flag[files[1].realindexes[yoff++]] = 1;
  272.   else if (yoff == ylim)
  273.     while (xoff < xlim)
  274.       files[0].changed_flag[files[0].realindexes[xoff++]] = 1;
  275.   else
  276.     {
  277.       int c, d, f, b;
  278.  
  279.       /* Find a point of correspondence in the middle of the files.  */
  280.  
  281.       d = diag (xoff, xlim, yoff, ylim, &c);
  282.       f = fdiag[d];
  283.       b = bdiag[d];
  284.  
  285.       if (c == 1)
  286.     {
  287.       /* This should be impossible, because it implies that
  288.          one of the two subsequences is empty,
  289.          and that case was handled above without calling `diag'.
  290.          Let's verify that this is true.  */
  291.       abort ();
  292. #if 0
  293.       /* The two subsequences differ by a single insert or delete;
  294.          record it and we are done.  */
  295.       if (d < xoff - yoff)
  296.         files[1].changed_flag[files[1].realindexes[b - d - 1]] = 1;
  297.       else
  298.         files[0].changed_flag[files[0].realindexes[b]] = 1;
  299. #endif
  300.     }
  301.       else
  302.     {
  303.       /* Use that point to split this problem into two subproblems.  */
  304.       compareseq (xoff, b, yoff, b - d);
  305.       /* This used to use f instead of b,
  306.          but that is incorrect!
  307.          It is not necessarily the case that diagonal d
  308.          has a snake from b to f.  */
  309.       compareseq (b, xlim, b - d, ylim);
  310.     }
  311.     }
  312. }
  313.  
  314. /* Discard lines from one file that have no matches in the other file.
  315.  
  316.    A line which is discarded will not be considered by the actual
  317.    comparison algorithm; it will be as if that line were not in the file.
  318.    The file's `realindexes' table maps virtual line numbers
  319.    (which don't count the discarded lines) into real line numbers;
  320.    this is how the actual comparison algorithm produces results
  321.    that are comprehensible when the discarded lines are counted.
  322.  
  323.    When we discard a line, we also mark it as a deletion or insertion
  324.    so that it will be printed in the output.  */
  325.  
  326. void
  327. discard_confusing_lines (filevec)
  328.      struct file_data filevec[];
  329. {
  330.   unsigned int f, i;
  331.   char *discarded[2];
  332.   int *equiv_count[2];
  333.  
  334.   /* Allocate our results.  */
  335.   for (f = 0; f < 2; f++)
  336.     {
  337.       filevec[f].undiscarded
  338.     = (int *) xmalloc (filevec[f].buffered_lines * sizeof (int));
  339.       filevec[f].realindexes
  340.     = (int *) xmalloc (filevec[f].buffered_lines * sizeof (int));
  341.     }
  342.  
  343.   /* Set up equiv_count[F][I] as the number of lines in file F
  344.      that fall in equivalence class I.  */
  345.  
  346.   equiv_count[0] = (int *) xmalloc (filevec[0].equiv_max * sizeof (int));
  347.   bzero (equiv_count[0], filevec[0].equiv_max * sizeof (int));
  348.   equiv_count[1] = (int *) xmalloc (filevec[1].equiv_max * sizeof (int));
  349.   bzero (equiv_count[1], filevec[1].equiv_max * sizeof (int));
  350.  
  351.   for (i = 0; i < filevec[0].buffered_lines; ++i)
  352.     ++equiv_count[0][filevec[0].equivs[i]];
  353.   for (i = 0; i < filevec[1].buffered_lines; ++i)
  354.     ++equiv_count[1][filevec[1].equivs[i]];
  355.  
  356.   /* Set up tables of which lines are going to be discarded.  */
  357.  
  358.   discarded[0] = (char *) xmalloc (filevec[0].buffered_lines);
  359.   discarded[1] = (char *) xmalloc (filevec[1].buffered_lines);
  360.   bzero (discarded[0], filevec[0].buffered_lines);
  361.   bzero (discarded[1], filevec[1].buffered_lines);
  362.  
  363.   /* Mark to be discarded each line that matches no line of the other file.
  364.      If a line matches many lines, mark it as provisionally discardable.  */
  365.  
  366.   for (f = 0; f < 2; f++)
  367.     {
  368.       unsigned int end = filevec[f].buffered_lines;
  369.       char *discards = discarded[f];
  370.       int *counts = equiv_count[1 - f];
  371.       int *equivs = filevec[f].equivs;
  372.       unsigned int many = 5;
  373.       unsigned int tem = end / 64;
  374.  
  375.       /* Multiply MANY by approximate square root of number of lines.
  376.      That is the threshold for provisionally discardable lines.  */
  377.       while ((tem = tem >> 2) > 0)
  378.     many *= 2;
  379.  
  380.       for (i = 0; i < end; i++)
  381.     {
  382.       int nmatch;
  383.       if (equivs[i] == 0)
  384.         continue;
  385.       nmatch = counts[equivs[i]];
  386.       if (nmatch == 0)
  387.         discards[i] = 1;
  388.       else if (nmatch > many)
  389.         discards[i] = 2;
  390.     }
  391.     }
  392.  
  393.   /* Don't really discard the provisional lines except when they occur
  394.      in a run of discardables, with nonprovisionals at the beginning
  395.      and end.  */
  396.  
  397.   for (f = 0; f < 2; f++)
  398.     {
  399.       unsigned int end = filevec[f].buffered_lines;
  400.       register char *discards = discarded[f];
  401.  
  402.       for (i = 0; i < end; i++)
  403.     {
  404.       /* Cancel provisional discards not in middle of run of discards.  */
  405.       if (discards[i] == 2)
  406.         discards[i] = 0;
  407.       else if (discards[i] != 0)
  408.         {
  409.           /* We have found a nonprovisional discard.  */
  410.           register int j;
  411.           unsigned int length;
  412.           unsigned int provisional = 0;
  413.  
  414.           /* Find end of this run of discardable lines.
  415.          Count how many are provisionally discardable.  */
  416.           for (j = i; j < end; j++)
  417.         {
  418.           if (discards[j] == 0)
  419.             break;
  420.           if (discards[j] == 2)
  421.             ++provisional;
  422.         }
  423.  
  424.           /* Cancel provisional discards at end, and shrink the run.  */
  425.           while (j > i && discards[j - 1] == 2)
  426.         discards[--j] = 0, --provisional;
  427.  
  428.           /* Now we have the length of a run of discardable lines
  429.          whose first and last are not provisional.  */
  430.           length = j - i;
  431.  
  432.           /* If 1/4 of the lines in the run are provisional,
  433.          cancel discarding of all provisional lines in the run.  */
  434.           if (provisional * 4 > length)
  435.         {
  436.           while (j > i)
  437.             if (discards[--j] == 2)
  438.               discards[j] = 0;
  439.         }
  440.           else
  441.         {
  442.           register unsigned int consec;
  443.           unsigned int minimum = 1;
  444.           unsigned int tem = length / 4;
  445.  
  446.           /* MINIMUM is approximate square root of LENGTH/4.
  447.              A subrun of two or more provisionals can stand
  448.              when LENGTH is at least 16.
  449.              A subrun of 4 or more can stand when LENGTH >= 64.  */
  450.           while ((tem = tem >> 2) > 0)
  451.             minimum *= 2;
  452.           minimum++;
  453.  
  454.           /* Cancel any subrun of MINIMUM or more provisionals
  455.              within the larger run.  */
  456.           for (j = 0, consec = 0; j < length; j++)
  457.             if (discards[i + j] != 2)
  458.               consec = 0;
  459.             else if (minimum == ++consec)
  460.               /* Back up to start of subrun, to cancel it all.  */
  461.               j -= consec;
  462.             else if (minimum < consec)
  463.               discards[i + j] = 0;
  464.  
  465.           /* Scan from beginning of run
  466.              until we find 3 or more nonprovisionals in a row
  467.              or until the first nonprovisional at least 8 lines in.
  468.              Until that point, cancel any provisionals.  */
  469.           for (j = 0, consec = 0; j < length; j++)
  470.             {
  471.               if (j >= 8 && discards[i + j] == 1)
  472.             break;
  473.               if (discards[i + j] == 2)
  474.             consec = 0, discards[i + j] = 0;
  475.               else if (discards[i + j] == 0)
  476.             consec = 0;
  477.               else
  478.             consec++;
  479.               if (consec == 3)
  480.             break;
  481.             }
  482.  
  483.           /* I advances to the last line of the run.  */
  484.           i += length - 1;
  485.  
  486.           /* Same thing, from end.  */
  487.           for (j = 0, consec = 0; j < length; j++)
  488.             {
  489.               if (j >= 8 && discards[i - j] == 1)
  490.             break;
  491.               if (discards[i - j] == 2)
  492.             consec = 0, discards[i - j] = 0;
  493.               else if (discards[i - j] == 0)
  494.             consec = 0;
  495.               else
  496.             consec++;
  497.               if (consec == 3)
  498.             break;
  499.             }
  500.         }
  501.         }
  502.     }
  503.     }
  504.  
  505.   /* Actually discard the lines. */
  506.   for (f = 0; f < 2; f++)
  507.     {
  508.       char *discards = discarded[f];
  509.       unsigned int end = filevec[f].buffered_lines;
  510.       unsigned int j = 0;
  511.       for (i = 0; i < end; ++i)
  512.     if (no_discards || discards[i] == 0)
  513.       {
  514.         filevec[f].undiscarded[j] = filevec[f].equivs[i];
  515.         filevec[f].realindexes[j++] = i;
  516.       }
  517.     else
  518.       filevec[f].changed_flag[i] = 1;
  519.       filevec[f].nondiscarded_lines = j;
  520.     }
  521.  
  522.   free (discarded[1]);
  523.   free (discarded[0]);
  524.   free (equiv_count[1]);
  525.   free (equiv_count[0]);
  526. }
  527.  
  528. /* Adjust inserts/deletes of blank lines to join changes
  529.    as much as possible.
  530.  
  531.    We do something when a run of changed lines include a blank
  532.    line at one end and have an excluded blank line at the other.
  533.    We are free to choose which blank line is included.
  534.    `compareseq' always chooses the one at the beginning,
  535.    but usually it is cleaner to consider the following blank line
  536.    to be the "change".  The only exception is if the preceding blank line
  537.    would join this change to other changes.  */
  538.  
  539. int inhibit;
  540.  
  541. static void
  542. shift_boundaries (filevec)
  543.      struct file_data filevec[];
  544. {
  545.   int f;
  546.  
  547.   if (inhibit)
  548.     return;
  549.  
  550.   for (f = 0; f < 2; f++)
  551.     {
  552.       char *changed = filevec[f].changed_flag;
  553.       char *other_changed = filevec[1-f].changed_flag;
  554.       int i = 0;
  555.       int j = 0;
  556.       int i_end = filevec[f].buffered_lines;
  557.       int preceding = -1;
  558.       int other_preceding = -1;
  559.  
  560.       while (1)
  561.     {
  562.       int start, end, other_start;
  563.  
  564.       /* Scan forwards to find beginning of another run of changes.
  565.          Also keep track of the corresponding point in the other file.  */
  566.  
  567.       while (i < i_end && changed[i] == 0)
  568.         {
  569.           while (other_changed[j++])
  570.         /* Non-corresponding lines in the other file
  571.            will count as the preceding batch of changes.  */
  572.         other_preceding = j;
  573.           i++;
  574.         }
  575.  
  576.       if (i == i_end)
  577.         break;
  578.  
  579.       start = i;
  580.       other_start = j;
  581.  
  582.       while (1)
  583.         {
  584.           /* Now find the end of this run of changes.  */
  585.  
  586.           while (i < i_end && changed[i] != 0) i++;
  587.           end = i;
  588.  
  589.           /* If the first changed line matches the following unchanged one,
  590.          and this run does not follow right after a previous run,
  591.          and there are no lines deleted from the other file here,
  592.          then classify the first changed line as unchanged
  593.          and the following line as changed in its place.  */
  594.  
  595.           /* You might ask, how could this run follow right after another?
  596.          Only because the previous run was shifted here.  */
  597.  
  598.           if (end != i_end
  599.           && files[f].equivs[start] == files[f].equivs[end]
  600.           && !other_changed[j]
  601.           && end != i_end
  602.           && !((preceding >= 0 && start == preceding)
  603.                || (other_preceding >= 0
  604.                && other_start == other_preceding)))
  605.         {
  606.           changed[end++] = 1;
  607.           changed[start++] = 0;
  608.           ++i;
  609.           /* Since one line-that-matches is now before this run
  610.              instead of after, we must advance in the other file
  611.              to keep in synch.  */
  612.           ++j;
  613.         }
  614.           else
  615.         break;
  616.         }
  617.  
  618.       preceding = i;
  619.       other_preceding = j;
  620.     }
  621.     }
  622. }
  623.  
  624. /* Cons an additional entry onto the front of an edit script OLD.
  625.    LINE0 and LINE1 are the first affected lines in the two files (origin 0).
  626.    DELETED is the number of lines deleted here from file 0.
  627.    INSERTED is the number of lines inserted here in file 1.
  628.  
  629.    If DELETED is 0 then LINE0 is the number of the line before
  630.    which the insertion was done; vice versa for INSERTED and LINE1.  */
  631.  
  632. static struct change *
  633. add_change (line0, line1, deleted, inserted, old)
  634.      int line0, line1, deleted, inserted;
  635.      struct change *old;
  636. {
  637.   struct change *new = (struct change *) xmalloc (sizeof (struct change));
  638.  
  639.   new->line0 = line0;
  640.   new->line1 = line1;
  641.   new->inserted = inserted;
  642.   new->deleted = deleted;
  643.   new->link = old;
  644.   return new;
  645. }
  646.  
  647. /* Scan the tables of which lines are inserted and deleted,
  648.    producing an edit script in reverse order.  */
  649.  
  650. static struct change *
  651. build_reverse_script (filevec)
  652.      struct file_data filevec[];
  653. {
  654.   struct change *script = 0;
  655.   char *changed0 = filevec[0].changed_flag;
  656.   char *changed1 = filevec[1].changed_flag;
  657.   int len0 = filevec[0].buffered_lines;
  658.   int len1 = filevec[1].buffered_lines;
  659.  
  660.   /* Note that changedN[len0] does exist, and contains 0.  */
  661.  
  662.   int i0 = 0, i1 = 0;
  663.  
  664.   while (i0 < len0 || i1 < len1)
  665.     {
  666.       if (changed0[i0] || changed1[i1])
  667.     {
  668.       int line0 = i0, line1 = i1;
  669.  
  670.       /* Find # lines changed here in each file.  */
  671.       while (changed0[i0]) ++i0;
  672.       while (changed1[i1]) ++i1;
  673.  
  674.       /* Record this change.  */
  675.       script = add_change (line0, line1, i0 - line0, i1 - line1, script);
  676.     }
  677.  
  678.       /* We have reached lines in the two files that match each other.  */
  679.       i0++, i1++;
  680.     }
  681.  
  682.   return script;
  683. }
  684.  
  685. /* Scan the tables of which lines are inserted and deleted,
  686.    producing an edit script in forward order.  */
  687.  
  688. static struct change *
  689. build_script (filevec)
  690.      struct file_data filevec[];
  691. {
  692.   struct change *script = 0;
  693.   char *changed0 = filevec[0].changed_flag;
  694.   char *changed1 = filevec[1].changed_flag;
  695.   int len0 = filevec[0].buffered_lines;
  696.   int len1 = filevec[1].buffered_lines;
  697.   int i0 = len0, i1 = len1;
  698.  
  699.   /* Note that changedN[-1] does exist, and contains 0.  */
  700.  
  701. #if 0 /* Unnecessary since a line includes its trailing newline.  */
  702.   /* In RCS comparisons, making the existence or nonexistence of trailing
  703.      newlines really matter. */
  704.   if (output_style == OUTPUT_RCS
  705.       && filevec[0].missing_newline != filevec[1].missing_newline)
  706.     changed0[len0 - 1] = changed1[len1 - 1] = 1;
  707. #endif
  708.  
  709.   while (i0 >= 0 || i1 >= 0)
  710.     {
  711.       if (changed0[i0 - 1] || changed1[i1 - 1])
  712.     {
  713.       int line0 = i0, line1 = i1;
  714.  
  715.       /* Find # lines changed here in each file.  */
  716.       while (changed0[i0 - 1]) --i0;
  717.       while (changed1[i1 - 1]) --i1;
  718.  
  719.       /* Record this change.  */
  720.       script = add_change (i0, i1, line0 - i0, line1 - i1, script);
  721.     }
  722.  
  723.       /* We have reached lines in the two files that match each other.  */
  724.       i0--, i1--;
  725.     }
  726.  
  727.   return script;
  728. }
  729.  
  730. /* Report the differences of two files.  DEPTH is the current directory
  731.    depth. */
  732. int
  733. diff_2_files (filevec, depth)
  734.      struct file_data filevec[];
  735.      int depth;
  736. {
  737.   long diags;
  738.   int i;
  739.   struct change *e, *p;
  740.   struct change *script;
  741.   int binary;
  742.   int changes;
  743.  
  744.   /* See if the two named files are actually the same physical file.
  745.      If so, we know they are identical without actually reading them.  */
  746.  
  747. #if !defined(MSDOS)
  748.       /*
  749.       ** since MSC always sets the inode and dev fields to zero under DOS
  750.       ** this test will always think two files are the same.
  751.       */
  752.   if (output_style != OUTPUT_IFDEF
  753.       && filevec[0].stat.st_ino == filevec[1].stat.st_ino
  754.       && filevec[0].stat.st_dev == filevec[1].stat.st_dev)
  755.     return 0;
  756. #endif /* MSDOS */
  757.  
  758.   if (no_details_flag
  759.       && (filevec[0].stat.st_mode & S_IFMT) == S_IFREG
  760.       && (filevec[1].stat.st_mode & S_IFMT) == S_IFREG
  761.       && filevec[0].stat.st_size != filevec[1].stat.st_size)
  762.     {
  763.       message ("Files %s and %s differ\n", filevec[0].name, filevec[1].name);
  764.       return 1;
  765.     }
  766.  
  767.   binary = read_files (filevec);
  768.  
  769.   /* If we have detected that file 0 is a binary file,
  770.      compare the two files as binary.  This can happen
  771.      only when the first chunk is read.
  772.      Also, -q means treat all files as binary.  */
  773.  
  774.   if (binary || no_details_flag)
  775.     {
  776. #if !defined(MSDOS)
  777.       int differs = (filevec[0].buffered_chars != filevec[1].buffered_chars
  778.              || bcmp (filevec[0].buffer, filevec[1].buffer,
  779.                   filevec[1].buffered_chars));
  780. #else
  781.       int differs;
  782.       if(filevec[0].buffered_chars != filevec[1].buffered_chars)
  783.               differs = 1;
  784.       else {
  785.               /*
  786.               ** we've got to do it in chunks because of our
  787.               ** poor 16 bit processor
  788.               */
  789.               char huge *b0 = filevec[0].buffer;
  790.               char huge *b1 = filevec[1].buffer;
  791.               long int count;
  792.               unsigned int delta;
  793.               count = filevec[0].buffered_chars;
  794.               while(count > 0) {
  795.                       delta = (unsigned)(count > 65000 ? 65000 : count);
  796.                       if(bcmp(b0,b1,delta) != 0)
  797.                               break;
  798.                       count -= delta;
  799.                       b0 += delta;
  800.                       b1 += delta;
  801.               }
  802.               differs = count != 0;
  803.       }
  804. #endif
  805.       if (differs) 
  806.     message (no_details_flag ? "Files %s and %s differ\n"
  807.          : "Binary files %s and %s differ\n",
  808.          filevec[0].name, filevec[1].name);
  809.  
  810.       for (i = 0; i < 2; ++i)
  811.     if (filevec[i].buffer)
  812. #ifndef MSDOS
  813.       free (filevec[i].buffer);
  814. #else
  815.           hfree (filevec[i].buffer);
  816. #endif
  817.       return differs;
  818.     }
  819.  
  820.   /* Allocate vectors for the results of comparison:
  821.      a flag for each line of each file, saying whether that line
  822.      is an insertion or deletion.
  823.      Allocate an extra element, always zero, at each end of each vector.  */
  824.  
  825.   filevec[0].changed_flag = (char *) xmalloc (filevec[0].buffered_lines + 2);
  826.   filevec[1].changed_flag = (char *) xmalloc (filevec[1].buffered_lines + 2);
  827.   bzero (filevec[0].changed_flag, filevec[0].buffered_lines + 2);
  828.   bzero (filevec[1].changed_flag, filevec[1].buffered_lines + 2);
  829.   filevec[0].changed_flag++;
  830.   filevec[1].changed_flag++;
  831.  
  832.   /* Some lines are obviously insertions or deletions
  833.      because they don't match anything.  Detect them now,
  834.      and avoid even thinking about them in the main comparison algorithm.  */
  835.  
  836.   discard_confusing_lines (filevec);
  837.  
  838.   /* Now do the main comparison algorithm, considering just the
  839.      undiscarded lines.  */
  840.  
  841.   xvec = filevec[0].undiscarded;
  842.   yvec = filevec[1].undiscarded;
  843.   diags = (long) filevec[0].nondiscarded_lines + filevec[1].nondiscarded_lines + 3;
  844. #ifdef MSDOS
  845.   fdiag = halloc (diags, sizeof (int));
  846.   bdiag = halloc (diags, sizeof (int));
  847.   if ( fdiag == NULL || bdiag == NULL )
  848.     fatal("virtual memory exhausted");
  849. #else
  850.   fdiag = (int *) xmalloc (diags * sizeof (int));
  851.   bdiag = (int *) xmalloc (diags * sizeof (int));
  852. #endif
  853.   fdiag += filevec[1].nondiscarded_lines + 1;
  854.   bdiag += filevec[1].nondiscarded_lines + 1;
  855.  
  856.   files[0] = filevec[0];
  857.   files[1] = filevec[1];
  858.  
  859.   compareseq (0, filevec[0].nondiscarded_lines,
  860.           0, filevec[1].nondiscarded_lines);
  861.  
  862.   bdiag -= filevec[1].nondiscarded_lines + 1;
  863.   fdiag -= filevec[1].nondiscarded_lines + 1;
  864. #ifdef MSDOS
  865.   hfree (bdiag);
  866.   hfree (fdiag);
  867. #else
  868.   free (bdiag);
  869.   free (fdiag);
  870. #endif
  871.  
  872.   /* Modify the results slightly to make them prettier
  873.      in cases where that can validly be done.  */
  874.  
  875.   shift_boundaries (filevec);
  876.  
  877.   /* Get the results of comparison in the form of a chain
  878.      of `struct change's -- an edit script.  */
  879.  
  880.   if (output_style == OUTPUT_ED)
  881.     script = build_reverse_script (filevec);
  882.   else
  883.     script = build_script (filevec);
  884.  
  885.   if (script || output_style == OUTPUT_IFDEF)
  886.     {
  887.       setup_output (files[0].name, files[1].name, depth);
  888.  
  889.       if (output_style == OUTPUT_CONTEXT ||
  890.           output_style == OUTPUT_UNIFIED ||
  891.           output_patch_flag)
  892.       print_context_header (files, output_style == OUTPUT_UNIFIED);
  893.  
  894.       switch (output_style)
  895.     {
  896.     case OUTPUT_CONTEXT:
  897.       /* print_context_header (files, 0); */
  898.       print_context_script (script, 0);
  899.       break;
  900.  
  901.     case OUTPUT_UNIFIED:
  902.       /* print_context_header (files, 1); */
  903.       print_context_script (script, 1);
  904.       break;
  905.  
  906.     case OUTPUT_ED:
  907.       print_ed_script (script);
  908.       break;
  909.  
  910.     case OUTPUT_FORWARD_ED:
  911.       pr_forward_ed_script (script);
  912.       break;
  913.  
  914.     case OUTPUT_RCS:
  915.       print_rcs_script (script);
  916.       break;
  917.  
  918.     case OUTPUT_NORMAL:
  919.       print_normal_script (script);
  920.       break;
  921.  
  922.     case OUTPUT_IFDEF:
  923.       print_ifdef_script (script);
  924.       break;
  925.  
  926.     case OUTPUT_MERGED:
  927.       print_merged_script (script);
  928.       break;
  929.     }
  930.  
  931.       finish_output ();
  932.     }
  933.  
  934.   /* Set CHANGES if we had any diffs that were printed.
  935.      If some changes are being ignored, we must scan the script to decide.  */
  936.   if (ignore_blank_lines_flag || ignore_regexp)
  937.     {
  938.       struct change *next = script;
  939.       changes = 0;
  940.  
  941.       while (next && changes == 0)
  942.     {
  943.       struct change *this, *end;
  944.       int first0, last0, first1, last1, deletes, inserts;
  945.  
  946.       /* Find a set of changes that belong together.  */
  947.       this = next;
  948.       end = find_change (next);
  949.  
  950.       /* Disconnect them from the rest of the changes,
  951.          making them a hunk, and remember the rest for next iteration.  */
  952.       next = end->link;
  953.       end->link = NULL;
  954.  
  955.       /* Determine whether this hunk was printed.  */
  956.       analyze_hunk (this, &first0, &last0, &first1, &last1,
  957.             &deletes, &inserts);
  958.  
  959.       /* Reconnect the script so it will all be freed properly.  */
  960.       end->link = next;
  961.  
  962.       if (deletes || inserts)
  963.         changes = 1;
  964.     }
  965.     }
  966.   else
  967.     changes = (script != 0);
  968.  
  969.   for (i = 1; i >= 0; --i)
  970.     {
  971.       free (filevec[i].realindexes);
  972.       free (filevec[i].undiscarded);
  973.     }
  974.  
  975.   for (i = 1; i >= 0; --i)
  976.     free (--filevec[i].changed_flag);
  977.  
  978.   for (i = 1; i >= 0; --i)
  979.     free (filevec[i].equivs);
  980.  
  981.   for (i = 0; i < 2; ++i)
  982.     {
  983. #if !defined(MSDOS)
  984.       if (filevec[i].buffer != 0)
  985.     free (filevec[i].buffer);
  986.  
  987.       free (filevec[i].linbuf);
  988. #else /* MSDOS */
  989.       if (filevec[i].buffer != 0)
  990.         hfree (filevec[i].buffer);
  991.  
  992.       hfree (filevec[i].linbuf);
  993. #endif
  994.     }
  995.  
  996.   for (e = script; e; e = p)
  997.     {
  998.       p = e->link;
  999.       free (e);
  1000.     }
  1001.  
  1002.   if (! ROBUST_OUTPUT_STYLE (output_style)
  1003.       /* For -D, invent newlines silently.  That's ok in C code.  */
  1004.       && output_style != OUTPUT_IFDEF)
  1005.     for (i = 0; i < 2; ++i)
  1006.       if (filevec[i].missing_newline)
  1007.     {
  1008.       error ("No newline at end of file %s", filevec[i].name, "");
  1009.       changes = 2;
  1010.     }
  1011.  
  1012.   return changes;
  1013. }
  1014.