require 'tempfile'

module LaTeX
  module ExternalDiff
    # Compute diffs using external diff command line tool
    # _seq1_ and _seq2_ are arrays of strings
    # Return value is array of arrays of the form:
    #
    #  [ code, l1, l2, r1, r2 ]
    #
    #  code:: "a", "d" or "c" for added, deleted, changed
    #  _l1_, _l2_, _r1_, _r2_:: line numbers from left and right files
    def self.diff(seq1,seq2)
      tf1 = Tempfile.new("seq1")
      tf2 = Tempfile.new("seq2")

      tf1.puts(seq1)
      tf2.puts(seq2)

      tf1.close
      tf2.close
      nl = "%c'\\012'"
      new_fmt = "a %dl %dl %dF %dL#{nl}"
      old_fmt = "d %df %dl %dL %dL#{nl}"
      changed_fmt = "c %df %dl %dF %dL#{nl}"
      unchanged_fmt = "e %df %dl %dF %dL#{nl}"

      cmd = %Q{diff -d --line-format= --new-group-format="#{new_fmt}" --old-group-format="#{old_fmt}" --changed-group-format="#{changed_fmt}" --unchanged-group-format="#{unchanged_fmt}" '#{tf1.path}' '#{tf2.path}'}

      if ENV['EXTERNALDIFF_DEBUG'] then
        $stderr.puts "Diffing"
        $stderr.puts seq1
        $stderr.puts "--------------"
        $stderr.puts seq2
        $stderr.puts "##############"
      end

      diffs = `#{cmd}`.map do |line| 
        code, l1,l2, r1,r2 = line.split
          [code, l1.to_i-1, l2.to_i-1, r1.to_i-1, r2.to_i-1]
                           end

      tf1.delete
      tf2.delete

      diffs
    end
  end
end
