require 'latex/parser'
require 'latex/diff'
require 'fileutils'
require 'yaml'

ENV['TEXINPUTS'] = '.:../../sty:'
ENV['DVIPSHEADERS'] = '.:../../sty:'

parse_out = "parse_out"
Dir.mkdir(parse_out) unless File.exists?(parse_out)

Dir["test-*-parse.tex"].each do |tex|
  parser = LaTeX::Parser.new
  begin
    tree = parser.parse_file(tex)
  rescue
    puts tex
    p $!
    p parser.seen[-10,10]
  end
  dump = YAML::dump(tree)
  expected_file = "#{tex}.yaml"
  output_file = File.join(parse_out,expected_file)
  
  File.open(output_file,"w") do |fp|
    fp.print dump
  end
  if not File.exists?(expected_file) then
    File.open(expected_file,"w") { |fp| fp.print dump }
  else
    expected = File.read(expected_file)
    if expected != dump then
      system "diff -u '#{expected_file}' '#{output_file}'"
      exit 1
    end
  end
end

tmpdir = "tmp"

FileUtils.rm_rf(tmpdir)
Dir.mkdir(tmpdir)    

preamble = File.read("../sty/pscbpreamble.tex")

Dir["test-*-old.tex"].each do |left|
  name = left[/test-(.*)-old\.tex/,1]
  right = left.gsub(/old\.tex/,"new.tex")
  
  $stderr.puts "Doing #{left} against #{right}"
  
  tree1 = LaTeX::Parser.new.parse_file(left)  
  tree2 = LaTeX::Parser.new.parse_file(right)  
  
  result = LaTeX::Diff.diff(tree1,tree2,preamble)
  
  Dir.chdir(tmpdir) do
    fname = "#{name}.tex"
    File.open(fname,"w") { |fp| fp.write(result) }
    status = system("latex #{fname}")
    exit 1 if !status
    status = system("dvips -Ppdf -o #{name}.ps #{name}.dvi")
    exit 1 if !status
    status = system("ps2pdf -sPAPERSIZE=a4 #{name}.ps")
    exit 1 if !status
  end
end

