#!/usr/bin/ruby

# May 2006, Ry Dahl, coldredlemur@gmail.com 


require "base64"

if ARGV[0] == nil or ARGV[1] == nil
  print """
This script takes an html file marked up with latex math equations 
(inside of dollar signs) and outputs the same file but with the 
equations replaced by image tags containing embedded png images of 
the equations.
You need latex and dvipng installed for it to work.

Usage: #{$0} (input html file) (output html file)

"""
  exit(0)
end

input = ARGV[0]
output = ARGV[1]

tmpdir = "/tmp/"
prefix = "#{tmpdir}/#{ENV['USER']}-#{input}"


f = File.new(input,"r")
html = f.read
f.close

re = Regexp.new('\$(.*?)\$', Regexp::MULTILINE)

eqncount = 0

tex = %q{
\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\pagestyle{empty}
\begin{document}
}

html.gsub(re) { |match|
  tex << "\\begin{equation*} #{$1} \\end{equation*} \\newpage \n\n"
  eqncount += 1
  "<<<<#{$1}>>>>"
}

tex << "\n \\end{document}"

texfn = "#{prefix}.tex"
texfile = File.open(texfn,'w')
texfile.write(tex)
texfile.close

# run latex on the file...
unless system("latex -halt-on-error -output-directory #{tmpdir} #{texfn}")
  puts "Latex failed."
  exit(0)
end

# now we split them into png files....
unless system("dvipng -gamma 2 -T tight -x 1200 -z 9 -o #{prefix}-%d.png #{prefix}.dvi")
  puts "dvipng failed."
  exit(0)
end

c = 1
html.gsub!(re) { |match|
  eqn = $1
  pngfilename = "#{prefix}-#{c}.png"
  f = File.open(pngfilename,"r")
  png = Base64.encode64(f.read)
  png.gsub!(/\s/,'')
  f.close
  
  # figure out the size of the file
  out = %x{identify -verbose #{pngfilename}}
  m = /Geometry: (\d.*)x(\d.*)/.match(out)
  width = m[1]
  height = m[2]  
    
  c += 1

  %Q{<img src="data:image/png;base64,#{png}" align="bottom" alt="#{eqn}" width=#{width} height=#{height} style="margin: 1px 4px 1px 4px;">}
}

# output the file
f = File.new(output,"w")
f << html
f.close
