src/util/diff/GnuDiff.java
public class GnuDiff {

  /**
   * Prepare to find differences between two arrays.  Each element of
   * the arrays is translated to an "equivalence number" based on
   * the result of <code>equals</code>.  The original Object arrays
   * are no longer needed for computing the differences.  They will
   * be needed again later to print the results of the comparison as
   * an edit script, if desired.
   */
  public GnuDiff(Object[] a, Object[] b) {
    Hashtable h = new Hashtable(a.length + b.length);
    filevec[0] = new file_data(a, h);
    filevec[1] = new file_data(b, h);
  }

  /**
   * 1 more than the maximum equivalence value used for this or its
   * sibling file.
   */
  private int equiv_max = 1;

  /**
   * When set to true, the comparison uses a heuristic to speed it up.
   * With this heuristic, for files with a constant small density
   * of changes, the algorithm is linear in the file size.
   */
  public boolean heuristic = false;

  /**
   * When set to true, the algorithm returns a guarranteed minimal
   * set of changes.  This makes things slower, sometimes much slower.
   */
  public boolean no_discards = true;

  private int[] xvec, yvec;  /* Vectors being compared. */
  private int[] fdiag;    /* Vector, indexed by diagonal, containing
				   the X coordinate of the point furthest
				   along the given diagonal in the forward
				   search of the edit matrix. */
  private int[] bdiag;    /* Vector, indexed by diagonal, containing
				   the X coordinate of the point furthest
				   along the given diagonal in the backward
				   search of the edit matrix. */
  private int fdiagoff, bdiagoff;
  private final file_data[] filevec = new file_data[2];
  private int cost;
  /**
   * Snakes bigger than this are considered "big".
   */
  private static final int SNAKE_LIMIT = 20;

  /**
   * Find the midpoint of the shortest edit script for a specified
   * portion of the two files.
   * <p/>
   * We scan from the beginnings of the files, and simultaneously from the ends,
   * doing a breadth-first search through the space of edit-sequence.
   * When the two searches meet, we have found the midpoint of the shortest
   * edit sequence.
   * <p/>
   * The value returned is the number of the diagonal on which the midpoint lies.
   * The diagonal number equals the number of inserted lines minus the number
   * of deleted lines (counting only lines before the midpoint).
   * The edit cost is stored into COST; this is the total number of
   * lines inserted or deleted (counting only lines before the midpoint).
   * <p/>
   * This function assumes that the first lines of the specified portions
   * of the two files do not match, and likewise that the last lines do not
   * match.  The caller must trim matching lines from the beginning and end
   * of the portions it is going to specify.
   * <p/>
   * Note that if we return the "wrong" diagonal value, or if
   * the value of bdiag at that diagonal is "wrong",
   * the worst this can do is cause suboptimal diff output.
   * It cannot cause incorrect diff output.
   */

  private int diag(int xoff, int xlim, int yoff, int ylim) {
    final int[] fd = fdiag;  // Give the compiler a chance.
    final int[] bd = bdiag;  // Additional help for the compiler.
    final int[] xv = xvec;    // Still more help for the compiler.
    final int[] yv = yvec;    // And more and more . . .
    final int dmin = xoff - ylim;  // Minimum valid diagonal.
    final int dmax = xlim - yoff;  // Maximum valid diagonal.
    final int fmid = xoff - yoff;  // Center diagonal of top-down search.
    final int bmid = xlim - ylim;  // Center diagonal of bottom-up search.
    int fmin = fmid, fmax = fmid;  // Limits of top-down search.
    int bmin = bmid, bmax = bmid;  // Limits of bottom-up search.
    /* True if southeast corner is on an odd
				     diagonal with respect to the northwest. */
    final boolean odd = (fmid - bmid & 1) != 0;

    fd[fdiagoff + fmid] = xoff;
    bd[bdiagoff + bmid] = xlim;

    for (int c = 1; ; ++c) {
      int d;      /* Active diagonal. */
      boolean big_snake = false;

      /* Extend the top-down search by an edit step in each diagonal. */
      if (fmin > dmin)
        fd[fdiagoff + --fmin - 1] = -1;
      else
        ++fmin;
      if (fmax < dmax)
        fd[fdiagoff + ++fmax + 1] = -1;
      else
        --fmax;
      for (d = fmax; d >= fmin; d -= 2) {
        int x, y, oldx, tlo = fd[fdiagoff + d - 1], thi = fd[fdiagoff + d + 1];

        if (tlo >= thi)
          x = tlo + 1;
        else
          x = thi;
        oldx = x;
        y = x - d;
        while (x < xlim && y < ylim && xv[x] == yv[y]) {
          ++x;
          ++y;
        }
        if (x - oldx > SNAKE_LIMIT)
          big_snake = true;
        fd[fdiagoff + d] = x;
        if (odd && bmin <= d && d <= bmax && bd[bdiagoff + d] <= fd[fdiagoff + d]) {
          cost = 2 * c - 1;
          return d;
        }
      }

      /* Similar extend the bottom-up search. */
      if (bmin > dmin)
        bd[bdiagoff + --bmin - 1] = Integer.MAX_VALUE;
      else
        ++bmin;
      if (bmax < dmax)
        bd[bdiagoff + ++bmax + 1] = Integer.MAX_VALUE;
      else
        --bmax;
      for (d = bmax; d >= bmin; d -= 2) {
        int x, y, oldx, tlo = bd[bdiagoff + d - 1], thi = bd[bdiagoff + d + 1];

        if (tlo < thi)
          x = tlo;
        else
          x = thi - 1;
        oldx = x;
        y = x - d;
        while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1]) {
          --x;
          --y;
        }
        if (oldx - x > SNAKE_LIMIT)
          big_snake = true;
        bd[bdiagoff + d] = x;
        if (!odd && fmin <= d && d <= fmax && bd[bdiagoff + d] <= fd[fdiagoff + d]) {
          cost = 2 * c;
          return d;
        }
      }

      /* Heuristic: check occasionally for a diagonal that has made
        lots of progress compared with the edit distance.
        If we have any such, find the one that has made the most
        progress and return it as if it had succeeded.

        With this heuristic, for files with a constant small density
        of changes, the algorithm is linear in the file size.  */

      if (c > 200 && big_snake && heuristic) {
        int best = 0;
        int bestpos = -1;

        for (d = fmax; d >= fmin; d -= 2) {
          int dd = d - fmid;
          int x = fd[fdiagoff + d];
          int y = x - d;
          int v = (x - xoff) * 2 - dd;
          if (v > 12 * (c + (dd < 0 ? -dd : dd))) {
            if (v > best
                    && xoff + SNAKE_LIMIT <= x && x < xlim
                    && yoff + SNAKE_LIMIT <= y && y < ylim) {
              /* We have a good enough best diagonal;
                now insist that it end with a significant snake.  */
              int k;

              for (k = 1; xvec[x - k] == yvec[y - k]; k++)
                if (k == SNAKE_LIMIT) {
                  best = v;
                  bestpos = d;
                  break;
                }
            }
          }
        }
        if (best > 0) {
          cost = 2 * c - 1;
          return bestpos;
        }

        best = 0;
        for (d = bmax; d >= bmin; d -= 2) {
          int dd = d - bmid;
          int x = bd[bdiagoff + d];
          int y = x - d;
          int v = (xlim - x) * 2 + dd;
          if (v > 12 * (c + (dd < 0 ? -dd : dd))) {
            if (v > best
                    && xoff < x && x <= xlim - SNAKE_LIMIT
                    && yoff < y && y <= ylim - SNAKE_LIMIT) {
              /* We have a good enough best diagonal;
                now insist that it end with a significant snake.  */
              int k;

              for (k = 0; xvec[x + k] == yvec[y + k]; k++)
                if (k == SNAKE_LIMIT) {
                  best = v;
                  bestpos = d;
                  break;
                }
            }
          }
        }
        if (best > 0) {
          cost = 2 * c - 1;
          return bestpos;
        }
      }
    }
  }

  /**
   * Compare in detail contiguous subsequences of the two files
   * which are known, as a whole, to match each other.
   * <p/>
   * The results are recorded in the vectors filevec[N].changed_flag, by
   * storing a 1 in the element for each line that is an insertion or deletion.
   * <p/>
   * The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
   * <p/>
   * Note that XLIM, YLIM are exclusive bounds.
   * All line numbers are origin-0 and discarded lines are not counted.
   */

  private void compareseq(int xoff, int xlim, int yoff, int ylim) {
    /* Slide down the bottom initial diagonal. */
    while (xoff < xlim && yoff < ylim && xvec[xoff] == yvec[yoff]) {
      ++xoff;
      ++yoff;
    }
    /* Slide up the top initial diagonal. */
    while (xlim > xoff && ylim > yoff && xvec[xlim - 1] == yvec[ylim - 1]) {
      --xlim;
      --ylim;
    }

    /* Handle simple cases. */
    if (xoff == xlim)
      while (yoff < ylim)
        filevec[1].changed_flag[1 + filevec[1].realindexes[yoff++]] = true;
    else if (yoff == ylim)
      while (xoff < xlim)
        filevec[0].changed_flag[1 + filevec[0].realindexes[xoff++]] = true;
    else {
      /* Find a point of correspondence in the middle of the files.  */

      int d = diag(xoff, xlim, yoff, ylim);
      int c = cost;
      int f = fdiag[fdiagoff + d];
      int b = bdiag[bdiagoff + d];

      if (c == 1) {
        /* This should be impossible, because it implies that
             one of the two subsequences is empty,
             and that case was handled above without calling `diag'.
             Let's verify that this is true.  */
        throw new IllegalArgumentException("Empty subsequence");
      } else {
        /* Use that point to split this problem into two subproblems.  */
        compareseq(xoff, b, yoff, b - d);
        /* This used to use f instead of b,
             but that is incorrect!
             It is not necessarily the case that diagonal d
             has a snake from b to f.  */
        compareseq(b, xlim, b - d, ylim);
      }
    }
  }

  /**
   * Discard lines from one file that have no matches in the other file.
   */

  private void discard_confusing_lines() {
    filevec[0].discard_confusing_lines(filevec[1]);
    filevec[1].discard_confusing_lines(filevec[0]);
  }

  private boolean inhibit = false;

  /**
   * Adjust inserts/deletes of blank lines to join changes
   * as much as possible.
   */

  private void shift_boundaries() {
    if (inhibit)
      return;
    filevec[0].shift_boundaries(filevec[1]);
    filevec[1].shift_boundaries(filevec[0]);
  }

  public interface ScriptBuilder {
    /**
     * Scan the tables of which lines are inserted and deleted,
     * producing an edit script.
     *
     * @param changed0 true for lines in first file which do not match 2nd
     * @param len0     number of lines in first file
     * @param changed1 true for lines in 2nd file which do not match 1st
     * @param len1     number of lines in 2nd file
     * @return a linked list of changes - or null
     */
    public change build_script(
            boolean[] changed0, int len0,
            boolean[] changed1, int len1
    );
  }

  /**
   * Scan the tables of which lines are inserted and deleted,
   * producing an edit script in reverse order.
   */

  static class ReverseScript implements ScriptBuilder {
    public change build_script(
            final boolean[] changed0, int len0,
            final boolean[] changed1, int len1) {
      change script = null;
      int i0 = 0, i1 = 0;
      while (i0 < len0 || i1 < len1) {
        if (changed0[1 + i0] || changed1[1 + i1]) {
          int line0 = i0, line1 = i1;

          /* Find # lines changed here in each file.  */
          while (changed0[1 + i0]) ++i0;
          while (changed1[1 + i1]) ++i1;

          /* Record this change.  */
          script = new change(line0, line1, i0 - line0, i1 - line1, script);
        }

        /* We have reached lines in the two files that match each other.  */
        i0++;
        i1++;
      }

      return script;
    }
  }

  static class ForwardScript implements ScriptBuilder {
    /**
     * Scan the tables of which lines are inserted and deleted,
     * producing an edit script in forward order.
     */
    public change build_script(
            final boolean[] changed0, int len0,
            final boolean[] changed1, int len1) {
      change script = null;
      int i0 = len0, i1 = len1;

      while (i0 >= 0 || i1 >= 0) {
        if (changed0[i0] || changed1[i1]) {
          int line0 = i0, line1 = i1;

          /* Find # lines changed here in each file.  */
          while (changed0[i0]) --i0;
          while (changed1[i1]) --i1;

          /* Record this change.  */
          script = new change(i0, i1, line0 - i0, line1 - i1, script);
        }

        /* We have reached lines in the two files that match each other.  */
        i0--;
        i1--;
      }

      return script;
    }
  }

  /**
   * Standard ScriptBuilders.
   */
  public final static ScriptBuilder
          forwardScript = new ForwardScript(),
          reverseScript = new ReverseScript();

  /* Report the differences of two files.  DEPTH is the current directory
     depth. */

  public final change diff_2(final boolean reverse) {
    return diff(reverse ? reverseScript : forwardScript);
  }

  /**
   * Get the results of comparison as an edit script.  The script
   * is described by a list of changes.  The standard ScriptBuilder
   * implementations provide for forward and reverse edit scripts.
   * Alternate implementations could, for instance, list common elements
   * instead of differences.
   *
   * @param bld an object to build the script from change flags
   * @return the head of a list of changes
   */
  public change diff(final ScriptBuilder bld) {

    /* Some lines are obviously insertions or deletions
       because they don't match anything.  Detect them now,
       and avoid even thinking about them in the main comparison algorithm.  */

    discard_confusing_lines();

    /* Now do the main comparison algorithm, considering just the
       undiscarded lines.  */

    xvec = filevec[0].undiscarded;
    yvec = filevec[1].undiscarded;

    int diags =
            filevec[0].nondiscarded_lines + filevec[1].nondiscarded_lines + 3;
    fdiag = new int[diags];
    fdiagoff = filevec[1].nondiscarded_lines + 1;
    bdiag = new int[diags];
    bdiagoff = filevec[1].nondiscarded_lines + 1;

    compareseq(0, filevec[0].nondiscarded_lines,
            0, filevec[1].nondiscarded_lines);
    fdiag = null;
    bdiag = null;

    /* Modify the results slightly to make them prettier
       in cases where that can validly be done.  */

    shift_boundaries();

    /* Get the results of comparison in the form of a chain
       of `struct change's -- an edit script.  */
    return bld.build_script(
            filevec[0].changed_flag,
            filevec[0].buffered_lines,
            filevec[1].changed_flag,
            filevec[1].buffered_lines
    );

  }

  /**
   * The result of comparison is an "edit script": a chain of change objects.
   * Each change represents one place where some lines are deleted
   * and some are inserted.
   * <p/>
   * LINE0 and LINE1 are the first affected lines in the two files (origin 0).
   * DELETED is the number of lines deleted here from file 0.
   * INSERTED is the number of lines inserted here in file 1.
   * <p/>
   * If DELETED is 0 then LINE0 is the number of the line before
   * which the insertion was done; vice versa for INSERTED and LINE1.
   */

  public static class change {
    /**
     * Previous or next edit command.
     */
    public change link;
    /**
     * # lines of file 1 changed here.
     */
    public final int inserted;
    /**
     * # lines of file 0 changed here.
     */
    public final int deleted;
    /**
     * Line number of 1st deleted line.
     */
    public final int line0;
    /**
     * Line number of 1st inserted line.
     */
    public final int line1;

    /**
     * Cons an additional entry onto the front of an edit script OLD.
     * LINE0 and LINE1 are the first affected lines in the two files (origin 0).
     * DELETED is the number of lines deleted here from file 0.
     * INSERTED is the number of lines inserted here in file 1.
     * <p/>
     * If DELETED is 0 then LINE0 is the number of the line before
     * which the insertion was done; vice versa for INSERTED and LINE1.
     */
    public change(int line0, int line1, int deleted, int inserted, change old) {
      this.line0 = line0;
      this.line1 = line1;
      this.inserted = inserted;
      this.deleted = deleted;
      this.link = old;
      //System.err.println(line0+","+line1+","+inserted+","+deleted);
    }
  }

  /**
   * Data on one input file being compared.
   */

  class file_data {

    /**
     * Allocate changed array for the results of comparison.
     */
    void clear() {
      /* Allocate a flag for each line of each file, saying whether that line
	 is an insertion or deletion.
	 Allocate an extra element, always zero, at each end of each vector.
       */
      changed_flag = new boolean[buffered_lines + 2];
    }

    /**
     * Return equiv_count[I] as the number of lines in this file
     * that fall in equivalence class I.
     *
     * @return the array of equivalence class counts.
     */
    int[] equivCount() {
      int[] equiv_count = new int[equiv_max];
      for (int i = 0; i < buffered_lines; ++i)
        ++equiv_count[equivs[i]];
      return equiv_count;
    }

    /**
     * Discard lines that have no matches in another file.
     * <p/>
     * A line which is discarded will not be considered by the actual
     * comparison algorithm; it will be as if that line were not in the file.
     * The file's `realindexes' table maps virtual line numbers
     * (which don't count the discarded lines) into real line numbers;
     * this is how the actual comparison algorithm produces results
     * that are comprehensible when the discarded lines are counted.
     * <p/>
     * When we discard a line, we also mark it as a deletion or insertion
     * so that it will be printed in the output.
     *
     * @param f the other file
     */
    void discard_confusing_lines(file_data f) {
      clear();
      /* Set up table of which lines are going to be discarded. */
      final byte[] discarded = discardable(f.equivCount());

      /* Don't really discard the provisional lines except when they occur
   in a run of discardables, with nonprovisionals at the beginning
   and end.  */
      filterDiscards(discarded);

      /* Actually discard the lines. */
      discard(discarded);
    }

    /**
     * Mark to be discarded each line that matches no line of another file.
     * If a line matches many lines, mark it as provisionally discardable.
     *
     * @param counts The count of each equivalence number for the other file.
     * @return 0=nondiscardable, 1=discardable or 2=provisionally discardable
     *         for each line
     * @see equivCount()
     */

    private byte[] discardable(final int[] counts) {
      final int end = buffered_lines;
      final byte[] discards = new byte[end];
      final int[] equivs = this.equivs;
      int many = 5;
      int tem = end / 64;

      /* Multiply MANY by approximate square root of number of lines.
	 That is the threshold for provisionally discardable lines.  */
      while ((tem = tem >> 2) > 0)
        many *= 2;

      for (int i = 0; i < end; i++) {
        int nmatch;
        if (equivs[i] == 0)
          continue;
        nmatch = counts[equivs[i]];
        if (nmatch == 0)
          discards[i] = 1;
        else if (nmatch > many)
          discards[i] = 2;
      }
      return discards;
    }

    /**
     * Don't really discard the provisional lines except when they occur
     * in a run of discardables, with nonprovisionals at the beginning
     * and end.
     */

    private void filterDiscards(final byte[] discards) {
      final int end = buffered_lines;

      for (int i = 0; i < end; i++) {
        /* Cancel provisional discards not in middle of run of discards.  */
        if (discards[i] == 2)
          discards[i] = 0;
        else if (discards[i] != 0) {
          /* We have found a nonprovisional discard.  */
          int j;
          int length;
          int provisional = 0;

          /* Find end of this run of discardable lines.
            Count how many are provisionally discardable.  */
          for (j = i; j < end; j++) {
            if (discards[j] == 0)
              break;
            if (discards[j] == 2)
              ++provisional;
          }

          /* Cancel provisional discards at end, and shrink the run.  */
          while (j > i && discards[j - 1] == 2) {
            discards[--j] = 0;
            --provisional;
          }

          /* Now we have the length of a run of discardable lines
            whose first and last are not provisional.  */
          length = j - i;

          /* If 1/4 of the lines in the run are provisional,
            cancel discarding of all provisional lines in the run.  */
          if (provisional * 4 > length) {
            while (j > i)
              if (discards[--j] == 2)
                discards[j] = 0;
          } else {
            int consec;
            int minimum = 1;
            int tem = length / 4;

            /* MINIMUM is approximate square root of LENGTH/4.
                 A subrun of two or more provisionals can stand
                 when LENGTH is at least 16.
                 A subrun of 4 or more can stand when LENGTH >= 64.  */
            while ((tem = tem >> 2) > 0)
              minimum *= 2;
            minimum++;

            /* Cancel any subrun of MINIMUM or more provisionals
                 within the larger run.  */
            for (j = 0, consec = 0; j < length; j++)
              if (discards[i + j] != 2)
                consec = 0;
              else if (minimum == ++consec)
                /* Back up to start of subrun, to cancel it all.  */
                j -= consec;
              else if (minimum < consec)
                discards[i + j] = 0;

            /* Scan from beginning of run
                 until we find 3 or more nonprovisionals in a row
                 or until the first nonprovisional at least 8 lines in.
                 Until that point, cancel any provisionals.  */
            for (j = 0, consec = 0; j < length; j++) {
              if (j >= 8 && discards[i + j] == 1)
                break;
              if (discards[i + j] == 2) {
                consec = 0;
                discards[i + j] = 0;
              } else if (discards[i + j] == 0)
                consec = 0;
              else
                consec++;
              if (consec == 3)
                break;
            }

            /* I advances to the last line of the run.  */
            i += length - 1;

            /* Same thing, from end.  */
            for (j = 0, consec = 0; j < length; j++) {
              if (j >= 8 && discards[i - j] == 1)
                break;
              if (discards[i - j] == 2) {
                consec = 0;
                discards[i - j] = 0;
              } else if (discards[i - j] == 0)
                consec = 0;
              else
                consec++;
              if (consec == 3)
                break;
            }
          }
        }
      }
    }

    /**
     * Actually discard the lines.
     *
     * @param discards flags lines to be discarded
     */
    private void discard(final byte[] discards) {
      final int end = buffered_lines;
      int j = 0;
      for (int i = 0; i < end; ++i)
        if (no_discards || discards[i] == 0) {
          undiscarded[j] = equivs[i];
          realindexes[j++] = i;
        } else
          changed_flag[1 + i] = true;
      nondiscarded_lines = j;
    }

    file_data(Object[] data, Hashtable h) {
      buffered_lines = data.length;

      equivs = new int[buffered_lines];
      undiscarded = new int[buffered_lines];
      realindexes = new int[buffered_lines];

      for (int i = 0; i < data.length; ++i) {
        Integer ir = (Integer) h.get(data[i]);
        if (ir == null)
          h.put(data[i], new Integer(equivs[i] = equiv_max++));
        else
          equivs[i] = ir.intValue();
      }
    }

    /**
     * Adjust inserts/deletes of blank lines to join changes
     * as much as possible.
     * <p/>
     * We do something when a run of changed lines include a blank
     * line at one end and have an excluded blank line at the other.
     * We are free to choose which blank line is included.
     * `compareseq' always chooses the one at the beginning,
     * but usually it is cleaner to consider the following blank line
     * to be the "change".  The only exception is if the preceding blank line
     * would join this change to other changes.
     *
     * @param f the file being compared against
     */

    void shift_boundaries(file_data f) {
      final boolean[] changed = changed_flag;
      final boolean[] other_changed = f.changed_flag;
      int i = 0;
      int j = 0;
      int i_end = buffered_lines;
      int preceding = -1;
      int other_preceding = -1;

      for (; ;) {
        int start, end, other_start;

        /* Scan forwards to find beginning of another run of changes.
           Also keep track of the corresponding point in the other file.  */

        while (i < i_end && !changed[1 + i]) {
          while (other_changed[1 + j++])
            /* Non-corresponding lines in the other file
             will count as the preceding batch of changes.  */
            other_preceding = j;
          i++;
        }

        if (i == i_end)
          break;

        start = i;
        other_start = j;

        for (; ;) {
          /* Now find the end of this run of changes.  */

          while (i < i_end && changed[1 + i]) i++;
          end = i;

          /* If the first changed line matches the following unchanged one,
          and this run does not follow right after a previous run,
          and there are no lines deleted from the other file here,
          then classify the first changed line as unchanged
          and the following line as changed in its place.  */

          /* You might ask, how could this run follow right after another?
          Only because the previous run was shifted here.  */

          if (end != i_end
                  && equivs[start] == equivs[end]
                  && !other_changed[1 + j]
                  && end != i_end
                  && !((preceding >= 0 && start == preceding)
                  || (other_preceding >= 0
                  && other_start == other_preceding))) {
            changed[1 + end++] = true;
            changed[1 + start++] = false;
            ++i;
            /* Since one line-that-matches is now before this run
               instead of after, we must advance in the other file
               to keep in synch.  */
            ++j;
          } else
            break;
        }

        preceding = i;
        other_preceding = j;
      }
    }

    /**
     * Number of elements (lines) in this file.
     */
    final int buffered_lines;

    /**
     * Vector, indexed by line number, containing an equivalence code for
     * each line.  It is this vector that is actually compared with that
     * of another file to generate differences.
     */
    private final int[] equivs;

    /**
     * Vector, like the previous one except that
     * the elements for discarded lines have been squeezed out.
     */
    final int[] undiscarded;

    /**
     * Vector mapping virtual line numbers (not counting discarded lines)
     * to real ones (counting those lines).  Both are origin-0.
     */
    final int[] realindexes;

    /**
     * Total number of nondiscarded lines.
     */
    int nondiscarded_lines;

    /**
     * Array, indexed by real origin-1 line number,
     * containing true for a line that is an insertion or a deletion.
     * The results of comparison are stored here.
     */
    boolean[] changed_flag;

  }
}
src/util/diff/GnuDiff.java
public static class change {
  /**
   * Previous or next edit command.
   */
  public change link;
  /**
   * # lines of file 1 changed here.
   */
  public final int inserted;
  /**
   * # lines of file 0 changed here.
   */
  public final int deleted;
  /**
   * Line number of 1st deleted line.
   */
  public final int line0;
  /**
   * Line number of 1st inserted line.
   */
  public final int line1;

  /**
   * Cons an additional entry onto the front of an edit script OLD.
   * LINE0 and LINE1 are the first affected lines in the two files (origin 0).
   * DELETED is the number of lines deleted here from file 0.
   * INSERTED is the number of lines inserted here in file 1.
   * <p/>
   * If DELETED is 0 then LINE0 is the number of the line before
   * which the insertion was done; vice versa for INSERTED and LINE1.
   */
  public change(int line0, int line1, int deleted, int inserted, change old) {
    this.line0 = line0;
    this.line1 = line1;
    this.inserted = inserted;
    this.deleted = deleted;
    this.link = old;
    //System.err.println(line0+","+line1+","+inserted+","+deleted);
  }
}
src/gui/botRight/ClipboardCopyHelpers.java
public class ClipboardCopyHelpers {

    static public String copySmart(SentinelHttpMessage httpMessage) {
        StringBuilder s = new StringBuilder();
        s.append("Request:\n");
        
        // GET
        s.append(httpMessage.getReq().extractFirstLine());
        s.append("\r\n");
        
        // HEADER
        List<String> headers = httpMessage.getReq().extractHeaders();
        Pattern pattern = Pattern.compile("^Host:", Pattern.CASE_INSENSITIVE);
        for (String header: headers) {
            Matcher matcher = pattern.matcher(header);
            if (matcher.find()) {
                s.append(header);
                s.append("\r\n");
            }
        }
        s.append("[CUT]\r\n");
        
        // BODY
        String b = httpMessage.getReq().extractBody();
        if (b.length() > 0) {
            s.append(b);
            s.append("\r\n");
        }

        // Delimiter
        s.append("\r\n");

        
        s.append("Response:\r\n");
        // HTTP
        s.append(httpMessage.getRes().extractFirstLine());
        s.append("\r\n");
        
        // HEADER
        headers = httpMessage.getRes().extractHeaders();
        Pattern patternDate = Pattern.compile("^Date:", Pattern.CASE_INSENSITIVE);
        Pattern patternContentType = Pattern.compile("^Content-Type:", Pattern.CASE_INSENSITIVE);
        for (String header: headers) {
            Matcher matcher = patternDate.matcher(header);
            if (matcher.find()) {
                s.append(header);
                s.append("\r\n");
            }
            
             matcher = patternContentType.matcher(header);
            if (matcher.find()) {
                s.append(header);
                s.append("\r\n");
            }
        }
        s.append("[CUT]\r\n");
        
        // BODY
        b = httpMessage.getRes().extractBody();
        if (b.length() > 0) {
            s.append(b);
            s.append("\r\n");
        }

        return s.toString();
    }
}
src/gui/session/SessionManager.java
public class SessionManager extends Observable {

    private static SessionManager sessionManager;
    private SessionManagerUi sessionManagerUi;
        
    
    public SessionManager() {
        this.sessionManagerUi = new SessionManagerUi();
    }
    
    public static SessionManager getInstance() {
        if (sessionManager == null) {
            sessionManager = new SessionManager();
        }
        
        return sessionManager;
    }
    
    public SessionManagerUi getSessionManagerUi() {
        return sessionManagerUi;
    }

    public int getUserCount() {
        return sessionManagerUi.getUserCount();
    }

    public SessionUser getUserAt(int newIndex) {
        return sessionManagerUi.getUserAt(newIndex);
    }

    public String getSessionVarName() {
        return sessionManagerUi.getSessionVarName();
    }

    public String getValueFor(String selectedSessionUser) {
        return sessionManagerUi.getSessionValueFor(selectedSessionUser);
    }

    public LinkedList<SessionUser> getSessionUsers() {
        return sessionManagerUi.getSessionUsers();
    }

    public SessionUser getUserFor(String value) {
        for (int n = 0; n < getUserCount(); n++) {
            SessionUser u = getUserAt(n);

            if (value.equals(u.getValue())) {
                return u;
            }
        }
        
        return null;
    }

    void myNotify() {
        this.setChanged();
        this.notifyObservers();
    }
    
}
src/model/SentinelHttpMessageAtk.java
public class SentinelHttpMessageAtk extends SentinelHttpMessage implements Serializable {

    private SentinelHttpMessageOrig parentHttpMessage = null;
    private AttackResult attackResult;
    
    private String atkName;
    private int atkIndex;
    private String atkIdent;
    
     public SentinelHttpMessageAtk(SentinelHttpMessageOrig httpMessage, String atkName, int atkIndex, String atkIdent) {
         super(httpMessage);
         this.parentHttpMessage = httpMessage;
         
         this.atkName = atkName;
         this.atkIndex = atkIndex;
         this.atkIdent = atkIdent;
         
         parentHttpMessage.addChildren(this);
    }

    public enum ObserveResult {
        REQUEST,
        RESPONSE,
        ATTACKRESULT,
        CHILDREN
    };
    
    public String getAtkIdent() {
        return atkIdent;
    }
    
    public void addAttackResult(AttackResult res) {
        // Add result
        this.attackResult = res;
 
        // Fire update event
        this.setChanged();
        this.notifyObservers(ObserveResult.ATTACKRESULT);
        
        this.parentHttpMessage.notifyAttackResult();
    }

    public AttackResult getAttackResult() {
        return attackResult;
    }

    public SentinelHttpMessage getParentHttpMessage() {
        if (parentHttpMessage == null) {
            BurpCallbacks.getInstance().print("getParentHttpMessage: null");
        }
        return parentHttpMessage;
    }
 
}
src/model/SentinelHttpParam.java
public class SentinelHttpParam implements IParameter, Serializable {

    static final byte PARAM_PATH = 7;
    private byte type;
    private String name;
    private int nameStart;
    private int nameEnd;
    
    protected String value;
    protected int valueStart;
    protected int valueEnd;
    
    public SentinelHttpParam(IParameter burpParameter) {
        this.type = burpParameter.getType();

        this.name = burpParameter.getName();
        this.nameStart = burpParameter.getNameStart();
        this.nameEnd = burpParameter.getNameEnd();

        this.value = burpParameter.getValue();
        this.valueStart = burpParameter.getValueStart();
        this.valueEnd = burpParameter.getValueEnd();
    }

    public SentinelHttpParam(byte type,
            String name, int nameStart, int nameEnd,
            String value, int valueStart, int valueEnd)
    {
        this.type = type;
        this.name = name;
        this.nameStart = nameStart;
        this.nameEnd = nameEnd;
        this.value = value;
        this.valueStart = valueStart;
        this.valueEnd = valueEnd;
    }


    public String getTypeStr() {
        switch (type) {
            case 0:
                return "GET";
            case 1:
                return "POST";
            case 2:
                return "COOKIE";
            case 3:
                return "XML";
            case 4:
                return "XML_ATTR";
            case 5:
                return "MULTIPART";
            case 6:
                return "JSON";
            case 7:
                return "PATH";
            default:
                return "unknown";
        }
    }

    public void changeValue(String value) {
        this.value = value;

        this.valueEnd = this.valueStart + value.length();
    }

    @Override
    public String getName() {
        return name;
    }

    public String getDecodedValue() {
        return value;
    }
    
    @Override
    public String getValue() {
        return value;
    }

    public int getValueLen() {
        return valueEnd - valueStart;
    }

    @Override
    public byte getType() {
        return type;
    }

    public int getNameLen() {
        return nameEnd - nameStart;
    }

    @Override
    public int getNameStart() {
        return nameStart;
    }

    @Override
    public int getNameEnd() {
        return nameEnd;
    }

    @Override
    public int getValueStart() {
        return valueStart;
    }

    @Override
    public int getValueEnd() {
        return valueEnd;
    }

    boolean isThisParameter(IParameter newParam) {
        if (getName().equals(newParam.getName()) && getType() == newParam.getType()) {
            return true;
        } else {
            return false;
        }
    }

    void updateLocationWith(IParameter newParam) {
        this.valueStart = newParam.getValueStart();
        this.valueEnd = newParam.getValueEnd();
        this.nameStart = newParam.getNameStart();
        this.nameEnd = newParam.getNameEnd();
    }
}
src/util/diff/DiffPrint.java
public static class UnifiedSmallPrint extends ContextPrint {

  public UnifiedSmallPrint(Object[] a, Object[] b) {
    super(a, b);
  }

  public void print_header(String filea, String fileb) {
    print_context_label("---", new File(filea), filea);
    print_context_label("+++", new File(fileb), fileb);
  }

  private void print_number_range(int a, int b) {
    //translate_range (file, a, b, &trans_a, &trans_b);

    /* Note: we can have B < A in the case of a range of no lines.
In this case, we should print the line number before the range,
which is B.  */
    if (b < a)
      outfile.print(b + ",0");
    else
      super.print_number_range(',', a, b);
  }

  protected void print_hunk(GnuDiff.change hunk) {
    /* Determine range of line numbers involved in each file.  */
    analyze_hunk(hunk);

    if (deletes == 0 && inserts == 0)
      return;

    /* Include a context's width before and after.  */

    first0 = Math.max(first0 - context, 0);
    first1 = Math.max(first1 - context, 0);
    last0 = Math.min(last0 + context, file0.length - 1);
    last1 = Math.min(last1 + context, file1.length - 1);

   //outfile.print("@@ -");
   // print_number_range(first0, last0);
   // outfile.print(" +");
   // print_number_range(first1, last1);
   // outfile.print(" @@");

    /* If we looked for and found a function this is part of,
include its name in the header of the diff section.  */
    print_function(file0, first0);

    outfile.println();

    GnuDiff.change next = hunk;
    int i = first0;
    int j = first1;

    while (i <= last0 || j <= last1) {

      /* If the line isn't a difference, output the context from file 0. */

      if (next == null || i < next.line0) {
        if (i < file0.length) {
          //outfile.print(' ');
          //print_1_line("", file0[i++]);
            i++;
        }
        j++;
      } else {
        /* For each difference, first output the deleted part. */

        int k = next.deleted;
        while (k-- > 0) {
          outfile.print('-');
          print_1_line("", file0[i++]);
        }

        /* Then output the inserted part. */

        k = next.inserted;
        while (k-- > 0) {
          outfile.print('+');
          print_1_line("", file1[j++]);
        }

        /* We're done with this hunk, so on to the next! */

        next = next.link;
      }
    }
  }
}
src/model/SentinelHttpMessage.java
public abstract class SentinelHttpMessage extends Observable implements IHttpRequestResponse, Serializable {

    private SentinelHttpResponse httpResponse;
    private SentinelHttpRequest httpRequest;
    private String comment;
    private SentinelHttpService httpService;
    private Date createTime;
    private long loadTime = 0;

    public SentinelHttpMessage() {
        // Deserializing Constructor
    }

    public SentinelHttpMessage(IHttpRequestResponse httpMessage) {
        httpRequest = new SentinelHttpRequest(httpMessage);
        httpService = new SentinelHttpService(httpMessage.getHttpService());
        httpResponse = new SentinelHttpResponse(httpMessage);

        createTime = new Date(System.currentTimeMillis());
        comment = httpMessage.getComment();
    }

    public SentinelHttpMessage(SentinelHttpMessage httpMessage) {
        this((IHttpRequestResponse) httpMessage);
        this.tableIndexMain = httpMessage.getTableIndexMain();
    }

    public SentinelHttpMessage(String s, String host, int port, boolean https) {
        httpService = new SentinelHttpService(host, port, https);
        httpRequest = new SentinelHttpRequest(s, httpService);

        httpResponse = new SentinelHttpResponse();

        createTime = new Date(System.currentTimeMillis());
    }

    /*public SentinelHttpMessage(String s, IHttpService httpService) {
        this.httpService = new SentinelHttpService(httpService);
        httpRequest = new SentinelHttpRequest(s, httpService);

        createTime = new Date(System.currentTimeMillis());
    }*/

    public SentinelHttpRequest getReq() {
        return httpRequest;
    }

    public SentinelHttpResponse getRes() {
        return httpResponse;
    }

    public Date getCreateTime() {
        return createTime;
    }
    private boolean isRedirected;

    public void setLoadTime(long time) {
        this.loadTime = time;
    }

    public long getLoadTime() {
        return loadTime;
    }

    public void setRedirected(boolean b) {
        isRedirected = b;
    }

    public boolean isRedirected() {
        return isRedirected;
    }

////////////////////////////////////////////////
    @Override
    public String getHighlight() {
        BurpCallbacks.getInstance().print("NOT SUPPORTED");
        return "";
    }

    @Override
    public void setHighlight(String color) {
        BurpCallbacks.getInstance().print("NOT SUPPORTED");
    }

    @Override
    public IHttpService getHttpService() {
        return httpService;
    }

    @Override
    public void setHttpService(IHttpService httpService) {
        this.httpService = new SentinelHttpService(httpService);
    }


    @Override
    public byte[] getRequest() {
        return httpRequest.getRequestByte();
    }

    @Override
    public void setRequest(byte[] message) {
        httpRequest = new SentinelHttpRequest(message, httpService);
    }

    @Override
    public byte[] getResponse() {
        return httpResponse.getByteResponse();
    }

    @Override
    public void setResponse(byte[] message) {
        httpResponse = new SentinelHttpResponse(message);
        notifyResponseContentChange();
    }
    
        
    void notifyResponseContentChange() {
        this.setChanged();
        this.notifyObservers();
    }
    


    @Override
    public String getComment() {
        return comment;
    }

    @Override
    public void setComment(String comment) {
        this.comment = comment;
    }
    /**
     * *****************************************
     */
    private int tableIndexMain = -1;

    public int getTableIndexMain() {
        return tableIndexMain;
    }

    public void setTableIndexMain(int index) {
        this.tableIndexMain = index;
    }
    private int tableIndexAttack = -1;

    public int getTableIndexAttack() {
        return tableIndexAttack;
    }

    public void setTableIndexAttack(int index) {
        this.tableIndexAttack = index;
    }
}
src/model/SentinelHttpMessageOrig.java
public class SentinelHttpMessageOrig extends SentinelHttpMessage implements Serializable {
    // Children
    private LinkedList<SentinelHttpMessageAtk> httpMessageChildren = new LinkedList<SentinelHttpMessageAtk>();
    private int messageNr = -1;
    
    public SentinelHttpMessageOrig(IHttpRequestResponse httpMessage) {
        super(httpMessage);
    }
    
    public SentinelHttpMessageOrig(String s, String host, int port, boolean https) {
        super(s, host, port, https);
    }
    
    public void addChildren(SentinelHttpMessageAtk aThis) {
        this.httpMessageChildren.add(aThis);
    }

    public LinkedList<SentinelHttpMessageAtk> getHttpMessageChildren() {
        return httpMessageChildren;
    }

    public Date getModifyTime() {
        Date newestDate = null;
        for (SentinelHttpMessage child : httpMessageChildren) {
            if (newestDate == null) {
                newestDate = child.getCreateTime();
            } else {
                Date childDate = child.getCreateTime();
                if (childDate.after(newestDate)) {
                    newestDate = childDate;
                }
            }
        }

        return newestDate;
    }

    void notifyAttackResult() {
        this.setChanged();
        this.notifyObservers(SentinelHttpMessageAtk.ObserveResult.ATTACKRESULT);
    }

    public void setSentinelIdentifier(int lastMessageNr) {
        this.messageNr = lastMessageNr;
    }
    
    public int getMessageNr() {
        return messageNr;
    }

}
src/gui/session/SessionUser.java
public class SessionUser {
    
    private String name;
    private String value;
    
    public SessionUser(String name, String value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    void setName(String name) {
        this.name = name;
    }
    
    void setValue(String value) {
        this.value = value;
    }
    
}
src/util/SettingsManager.java
public class SettingsManager {

    private static Theme theme = null;
    
    public static void resetConfig() {
        BurpCallbacks.getInstance().print("Reset config");
        try {
            //Preferences.userRoot().removeNode();
            
            for (String s: Preferences.userRoot().childrenNames()) {
                
                BurpCallbacks.getInstance().print("Remove: " + s);
                for (String ss: Preferences.userRoot().node(s).keys()) {
                    BurpCallbacks.getInstance().print("remove 1: " + ss);
                    Preferences.userRoot().node(s).remove(ss);
                }
            }
            
            Preferences.userRoot().flush();
        } catch (BackingStoreException ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    public static Theme getTheme() {
        if (theme == null) {
            try {
                InputStream in = SettingsManager.class.getResourceAsStream("/resources/BurpTheme.xml");
                theme = Theme.load(in);
            } catch (IOException ex) {
                BurpCallbacks.getInstance().print("error loading theme: " + ex.getLocalizedMessage());
            }
        }
        return theme;
    }
    
    public static void storeTableDimensions(JTable table, Object o) {
        Preferences pref = Preferences.userRoot().node(o.getClass().getName());
        TableColumnModel columns = table.getColumnModel();

        for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
            TableColumn column = columns.getColumn(i);
            int w = column.getPreferredWidth();
            
            pref.putInt(Integer.toString(i), w);
        }
    }

    public static void restoreTableDimensions(JTable table, Object o) {
        Preferences pref = Preferences.userRoot().node(o.getClass().getName());
        TableColumnModel columns = table.getColumnModel();
        

        for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
            TableColumn column = columns.getColumn(i);
            int w = pref.getInt(Integer.toString(i), 10);
    

            column.setPreferredWidth(w);
        }
    }
    
    
    /** Store location & size of UI */
    public static void storeFrameDimensions(Frame f, Object o) {
        Preferences pref = Preferences.userRoot().node(o.getClass().getName());
       
        // restore the frame from 'full screen' first!
        f.setExtendedState(Frame.NORMAL);
        Rectangle r = f.getBounds();
        
        int x = (int)r.getX();
        int y = (int)r.getY();
        int w = (int)r.getWidth();
        int h = (int)r.getHeight();
        
        pref.putInt("x", x);
        pref.putInt("y", y);
        pref.putInt("w", w);
        pref.putInt("h", h);
    }

    /** Restore location & size of UI */
    public static void restoreFrameDimensions(Frame f, Object o) {
        Preferences pref = Preferences.userRoot().node(o.getClass().getName());

        int x = pref.getInt("x", 0);
        int y = pref.getInt("y", 0);
        int w = pref.getInt("w", 1024);
        int h = pref.getInt("h", 786);

        Rectangle r = new Rectangle(x,y,w,h);
        f.setBounds(r);
    }
    

    public static void storeSplitLocation(JSplitPane jSplitPane1, Object o) {
        Preferences pref = Preferences.userRoot().node(o.getClass().getName());
        pref.putInt(("location"), jSplitPane1.getDividerLocation());
    }

    public static void restoreSplitLocation(JSplitPane jSplitPane1, Object o) {
        Preferences pref = Preferences.userRoot().node(o.getClass().getName());
        jSplitPane1.setDividerLocation(pref.getInt(("location"), jSplitPane1.getDividerLocation()));
    }

    public static void storeSessions(LinkedList<SessionUser> sessionUsers) {
        Preferences pref = Preferences.userRoot().node("SessionManagerUsers");
        try {
            pref.clear();
        } catch (BackingStoreException ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        for(SessionUser u: sessionUsers) {
            pref.put(u.getName(), u.getValue());
        }
    }
    
    public static void restoreSessions(LinkedList<SessionUser> sessionUsers) {
        Preferences pref = Preferences.userRoot().node("SessionManagerUsers");
    
        String[] children = null;
        try {
            children = pref.keys();
            for (String s : children) {
                String value = pref.get(s, "");
                sessionUsers.add(new SessionUser(s, value));
            }            
        } catch (BackingStoreException ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    

    public static void storeSessionData(String text) {
        Preferences pref = Preferences.userRoot().node("SessionManagerData");
        pref.put("SessionVarName", text);
    }

    public static void restoreSessionData(JTextField textfieldSession) {
        Preferences pref = Preferences.userRoot().node("SessionManagerData");
        
        String s = pref.get("SessionVarName", "jsessionid");
        textfieldSession.setText(s);
    }

    
    public static boolean getCategoryInitState() {
        Preferences pref = Preferences.userRoot().node("Initialization");
        return pref.getBoolean("CategoryLoading", false);
    }
    
    public static void setCategoryInitState(boolean b) {
        Preferences pref = Preferences.userRoot().node("Initialization");
        pref.putBoolean("CategoryLoading", b);
    }
    
    public static void restoreCategories(Category category) {
        Preferences pref = Preferences.userRoot().node("CategoryEntries" + category.getName());
    
        int n=0;
        int last = pref.getInt("numbers", 0);
        
        LinkedList<CategoryEntry> categoryEntries = new LinkedList<CategoryEntry>();
        
        for(n=0; n<last; n++) {
            String tag = pref.get(Integer.toString(n) + "_tag", "");
            String regex = pref.get(Integer.toString(n) + "_regex", "");
            Color c = new Color (pref.getInt(Integer.toString(n) + "_color", 0));
            boolean enabled = pref.getBoolean(Integer.toString(n) + "_enabled", true);
            categoryEntries.add( new CategoryEntry (tag, regex, c, enabled));
        }
        category.setCategoryEntries(categoryEntries);
    }

    public static void storeCategory(Category category) {
        Preferences pref = Preferences.userRoot().node("CategoryEntries" + category.getName());
        try {
            pref.clear();
        } catch (BackingStoreException ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        int n = 0;
        for(CategoryEntry c: category.getCategoryEntries()) {
            pref.put(Integer.toString(n) + "_tag", c.getTag());
            pref.put(Integer.toString(n) + "_regex", c.getRegex());
            pref.putInt(Integer.toString(n) + "_color", c.getColor().getRGB());
            pref.putBoolean(Integer.toString(n) + "_enabled", c.isEnabled());
            n++;
        }
        pref.putInt("numbers", n);
    }


    public static void storeAttackLists(LinkedList<ListManagerList> lists) {
        Preferences pref = Preferences.userRoot().node("AttackLists");
        try {
            pref.clear();
        } catch (BackingStoreException ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        for(ListManagerList list: lists) {
            if (! list.isFuzzDB()) {
                pref.put(list.getName(), list.getContentAsString());
            }
        }
    }
    
    public static void restoreAttackLists(LinkedList<ListManagerList> lists) {
        Preferences pref = Preferences.userRoot().node("AttackLists");
    
        String[] children = null;
        try {
            children = pref.keys();
            for (String s : children) {
                String value = pref.get(s, "");
                lists.add( new ListManagerList(s, value, false));
            }            
        } catch (BackingStoreException ex) {
            Logger.getLogger(SettingsManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static int getListInitState() {
        Preferences pref = Preferences.userRoot().node("Initialization");
        
        return pref.getInt("FuzzDb", 1);
    }
    
    public static void setListInitState(int b) {
        Preferences pref = Preferences.userRoot().node("Initialization");
        pref.putInt("FuzzDb", b);
    }

    public static void storePanelLeftOptionRedirect(boolean optionEnableRedirect) {
        Preferences pref = Preferences.userRoot().node("PanelLeftOptions");
        pref.putBoolean("FollowRedirect", optionEnableRedirect);
    }
    
    public static boolean restorePanelLeftOptionRedirect() {
        Preferences pref = Preferences.userRoot().node("PanelLeftOptions");
        return pref.getBoolean("FollowRedirect", true);
    }
    

    public static void storePanelLeftOptionPosition(InsertPositions optionInsertPosition) {
        Preferences pref = Preferences.userRoot().node("PanelLeftOptions");
        pref.put("InsertPosition", optionInsertPosition.toString());
    }
    
    public static InsertPositions restorePanelLeftOptionPosition() {
        Preferences pref = Preferences.userRoot().node("PanelLeftOptions");
        String res = pref.get("InsertPosition", "RIGHT");
        
        return InsertPositions.valueOf(res);
    }
    
    
    public static void storeEnableRelativeResponseSize(boolean b) {
        Preferences pref = Preferences.userRoot().node("Options");
        pref.putBoolean("RelativeResponseSize", b);
    }
    
    public static boolean getEnableRelativeResponseSize() {
        Preferences pref = Preferences.userRoot().node("Options");
        boolean res = pref.getBoolean("RelativeResponseSize", true);
        return res;
    }    
    

    public static SqlmapData getSqlmapConfig() {
        Preferences pref = Preferences.userRoot().node("Sqlmap");
        SqlmapData data = new SqlmapData();
     
        data.pythonPath = pref.get("PythonPath", "/usr/bin/python");
        data.sqlmapPath = pref.get("SqlmapPath", "/home/dobin/Downloads/sqlmapproject-sqlmap-cb1f17c/sqlmap.py");
        data.workingDir = pref.get("WorkingDir", "/tmp/sqlmap/");
        
        return data;
    }
    
    public static void storeSqlmapConfig(SqlmapData data) {
        Preferences pref = Preferences.userRoot().node("Sqlmap");
        
        pref.put("PythonPath", data.pythonPath);
        pref.put("SqlmapPath", data.sqlmapPath);
        pref.put("WorkingDir", data.workingDir);
    }

    
    public static void storeAttackSelectionConfig(List<AttackDescription> attacks) {
        Preferences pref = Preferences.userRoot().node("AttackSelection");
        
        for(AttackDescription attack: attacks) {
            pref.putBoolean(attack.getShort(), attack.isEnabled());
        }
    }
    
    
    public static void getAttackSelectionConfig(List<AttackDescription> attacks) {
        Preferences pref = Preferences.userRoot().node("AttackSelection");
        
        for(AttackDescription attack: attacks) {
            // Make sane defaults for new users: XSS and SQLE
            if (attack.getAttackType() == AttackTypes.XSS || attack.getAttackType() == AttackTypes.SQLE) {
                attack.setEnabled( pref.getBoolean(attack.getShort(), true) );
            } else {
                attack.setEnabled( pref.getBoolean(attack.getShort(), false) );
            }
        }
    }
    
}
src/model/ResponseHighlight.java
public class ResponseHighlight implements Serializable {
    private String str;
    private Color color;
    
    public ResponseHighlight(String str, Color color) {
        this.str = str;
        this.color = color;
    }
    
    public String getStr() {
        return str;
    }
    
    public Color getColor() {
        return color;
    }
    
}
src/util/BurpCallbacks.java
public class BurpCallbacks {

    static private BurpCallbacks burpCallbacks = null;
    private IBurpExtenderCallbacks callback;
    private PrintWriter stdout;

    public void init(IBurpExtenderCallbacks callback) {
        this.callback = callback;
        stdout = new PrintWriter(callback.getStdout(), true);
    }

    public IBurpExtenderCallbacks getBurp() {
        return callback;
    }

    public void print(String s) {
        if (stdout != null) {
            stdout.println(s);
        }
    }

    public static BurpCallbacks getInstance() {
        if (burpCallbacks == null) {
            burpCallbacks = new BurpCallbacks();
        }
        return burpCallbacks;
    }
    
    public void sendRessource(final SentinelHttpMessage sentinelMessage, final boolean followRedirect, final ExternalUpdater updater) {
        Thread queryThread = new Thread() {
            public void run() {
                try {
                    sendRessource(sentinelMessage, followRedirect);
                    
                    if (updater != null) {
                        updater.externalUpdate();
                    }
                } catch (ConnectionTimeoutException ex) {
                    BurpCallbacks.getInstance().print("Error sendingz");
                }
            }
        };
        queryThread.start();
        
    }

    public void sendRessource(SentinelHttpMessage httpMessage, boolean followRedirect) throws ConnectionTimeoutException {
        if (getBurp() == null) {
            BurpCallbacks.getInstance().print("sendRessource: No burp available. Abort.");
            return;
        }
        if (httpMessage == null) {
            BurpCallbacks.getInstance().print("sendRessource: Void httpmessage! See previous errors. Abort.");
            return;
        }
        if (httpMessage.getHttpService() == null || httpMessage.getRequest() == null) {
            BurpCallbacks.getInstance().print("sendRessource: Void data! Abort.");
            return;
        }
        
        BurpCallbacks.getInstance().print("sendRessource start");

        IHttpRequestResponse r = null;
        long timeStart = System.currentTimeMillis();
        r = getBurp().makeHttpRequest(httpMessage.getHttpService(), httpMessage.getRequest());
        long time = System.currentTimeMillis() - timeStart;
        httpMessage.setLoadTime(time);

        BurpCallbacks.getInstance().print("sendRessource end");

        if (r.getResponse() == null) {
            throw new ConnectionTimeoutException();
        }

        if (followRedirect) {
            int n = 0;
            while (isRedirect(r.getResponse()) && ++n <= 10) {
                BurpCallbacks.getInstance().print("Is redir, following...");
                httpMessage.setRedirected(true);
                r = followRedirect(r);
            }
            if (n >= 10) {
                String s = "Redirected 10 times, aborting...";
                httpMessage.setResponse(s.getBytes());
            } else {
                httpMessage.setResponse(r.getResponse());
            }
        } else {
            httpMessage.setResponse(r.getResponse());
        }
    }

    private boolean isRedirect(byte[] response) {
        IResponseInfo responseInfo = BurpCallbacks.getInstance().getBurp().getHelpers().analyzeResponse(response);
        if (responseInfo.getStatusCode() == 302) {
            return true;
        } else {
            return false;
        }
    }

    private IHttpRequestResponse followRedirect(IHttpRequestResponse r) {
        byte[] response = r.getResponse();
        
        IResponseInfo responseInfo = BurpCallbacks.getInstance().getBurp().getHelpers().analyzeResponse(response);
        String redirStr = null;

        for (String header : responseInfo.getHeaders()) {
            if (header.toLowerCase().startsWith("location: ")) {
                String[] h = header.split(": ");
                if (h.length == 2) {
                    redirStr = h[1];
                }
            }
        }

        if (redirStr == null) {
            BurpCallbacks.getInstance().print("302 found, but could not extract location header!");
            return null;
        }
        
        /* 302 has 3 possible values:
         * 1) http://www.bla.ch/asdf/test.cgi?a=b
         * 2) /asdf/test.cgi?a=b
         * 3) test.cgi?a=b
         * URL will handle all of em
         */
        
        URL redirUrl = null;
        redirUrl = followRedirectUrl(redirStr, r);
        if (redirUrl == null) {
            return null;
        }
        
        byte[] req = BurpCallbacks.getInstance().getBurp().getHelpers().buildHttpRequest(redirUrl);
        int port = redirUrl.getPort();
        if (port == -1) {
            port = redirUrl.getDefaultPort();
        }
        IHttpService httpService = new SentinelHttpService(
                redirUrl.getHost(), port, redirUrl.getProtocol());
        IHttpRequestResponse res = getBurp().makeHttpRequest(httpService, req);
        
        return res;
    }
    
    private URL followRedirectUrl(String redirStr, IHttpRequestResponse message) {
        // get old url
        System.out.println("FOLLOW!");
        IRequestInfo requestInfo = BurpCallbacks.getInstance().getBurp().getHelpers().analyzeRequest(message);
        URL origUrl = requestInfo.getUrl();
        
        // create new url
        URL url;
        try {
            url = new URL(origUrl, redirStr);
        } catch (MalformedURLException ex) {
            BurpCallbacks.getInstance().print("302 found, but could not convert location header!");
            return null;
        }
        
        return url;
    }

    public void sendToRepeater(SentinelHttpMessage httpMessage) {
        try {
            String s = "";
            if (httpMessage.getTableIndexAttack() >= 0) {
                s = "Sentinel " + httpMessage.getTableIndexMain() + "/" + httpMessage.getTableIndexAttack();
            } else {
                s = "Sentinel " + httpMessage.getTableIndexMain();
            }
            
            this.getBurp().sendToRepeater(
                    httpMessage.getHttpService().getHost(),
                    httpMessage.getHttpService().getPort(),
                    (httpMessage.getHttpService().getProtocol().equals("http") ? false : true),
                    httpMessage.getRequest(),
                    s);
        } catch (Exception ex) {
            BurpCallbacks.getInstance().print(ex.getLocalizedMessage());
        }
    }
}


Question: import gui.botRight.ClipboardCopyHelpers;
import model.ResponseHighlight;
import gui.session.SessionManager;
import gui.session.SessionUser;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoundedRangeModel;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import model.SentinelHttpMessage;
import model.SentinelHttpMessageAtk;
import model.SentinelHttpMessageOrig;
import model.SentinelHttpParam;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.fife.ui.rtextarea.SearchContext;
import org.fife.ui.rtextarea.SearchEngine;
import util.BurpCallbacks;
import util.SettingsManager;
import util.diff.DiffPrint.UnifiedSmallPrint;
import util.diff.GnuDiff;
import util.diff.GnuDiff.change;
/*
 * Copyright (C) 2013 DobinRutishauser@broken.ch
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gui.viewMessage;


/**
 * Displays httpMessages
 *
 * - Response with it's information - and the request - accumulates data to
 * highlight
 *
 *
 * @author Dobin
 */
public class PanelViewMessageUi extends javax.swing.JPanel implements ExternalUpdater {

    private SentinelHttpMessage httpMessage = null;
    private boolean showResponse = true;
    private PanelViewMessagePopup messagePopup;
    
    private PanelViewComboboxModel panelViewComboboxModel;
    
    private ViewMessageLinkManager linkManager = null;
    
    private int selectIndex = -1;
    private Object currentHighlight;
    
    private int savedCursor = -1;

    private BoundedRangeModel origScrollbarModel;
    
    private boolean isRequestEditor = false;
    
    private RSyntaxTextArea textareaMessage;
    private RTextScrollPane scrollPane;
    
    private String lastSearch = "";
    private SearchContext searchContext = null;
    
    private String currentView = "Default View";

    
    private LinkedList<SentinelHighlight> myHighlights;

    private SentinelHttpMessage diffHttpMessage;
    
       
    private String theme;
    
    
    /**
     * Creates new form PanelResponseUi
     */
    public PanelViewMessageUi() {
        panelViewComboboxModel = new PanelViewComboboxModel();
        
        initComponents();
        textareaMessage = new RSyntaxTextArea();
        scrollPane = new RTextScrollPane(textareaMessage);
        scrollPane.add(textareaMessage);
        panelCenter.removeAll();
        panelCenter.add(scrollPane, BorderLayout.CENTER);
        scrollPane.setViewportView(textareaMessage);

        this.invalidate();
        this.updateUI();
        
        panelHighlight.setVisible(false);
        
        messagePopup = new PanelViewMessagePopup(this);
        
        textareaMessage.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_HTML);
        textareaMessage.setEditable(true);
        textareaMessage.setLineWrap(true);
        textareaMessage.setWrapStyleWord(false);
        textareaMessage.setAnimateBracketMatching(false);
        textareaMessage.setAutoIndentEnabled(false);
        textareaMessage.setBracketMatchingEnabled(false);
        textareaMessage.setPopupMenu(messagePopup.getPopup());
        SettingsManager.getTheme().apply(textareaMessage);
        textareaMessage.revalidate(); // TODO necessary?
        textareaMessage.requestFocusInWindow();
        textareaMessage.setMarkAllHighlightColor(new Color(0xff, 0xea, 0x00, 100));
        
        labelPosition.setText(" ");
        
        origScrollbarModel = scrollPane.getVerticalScrollBar().getModel();

        comboboxView.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox)e.getSource();
                String selected = (String) cb.getSelectedItem();

                currentView = selected;
                showMessage();
            }
        });

        textfieldSearch.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                initSearchContext(textfieldSearch.getText());
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                initSearchContext(textfieldSearch.getText());
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                initSearchContext(textfieldSearch.getText());
            }
        });
    }
        

    public void setHttpMessage(SentinelHttpMessage httpMessage) {
        if (httpMessage == null) {
            BurpCallbacks.getInstance().print("setResponse(): HttpMessage NULL");
            return;
        }
        this.httpMessage = httpMessage;
        reInit();

    }

    private void reInit() {
        if (httpMessage.getRes().hasResponse()) {
Answer:             if (httpMessage instanceof SentinelHttpMessageOrig) {