#!/usr/bin/env ruby
require 'date'
$KCODE = "e"

# rd ファイル中に 「((#{ }))」 を埋め込む
def ruby_to_rd(file, outfile)
  rfile = open(file,"r")
  rdscpt =""
  rfile.each{ |i|
    if i =~ /\(\(#\{.*\}\)\)/
      i.split(/\(\(#\{/).each { |ii|
	if ii =~ /\}\)\)/
	  iii = ii.split(/\}\)\)/)[0]
	  iiii = `ruby  -e 'print #{iii}'`
	  rdscpt << iiii
	  rdscpt << ii.sub(/#{iii}\}\)\)/,"")
	else 
	  rdscpt << ii
	end
      }
    else 
      rdscpt << i 
    end
  }
  rfile.close
  File.delete(outfile) if File.exist?(outfile)
  wfile = open(outfile,"w") 
  wfile.print rdscpt
  wfile.close
#  File.rename("tmp.rd",file)
end

# rd ファイルから, tex 記述部を抽出, 削除
def tex_to_rd(file, outfile)

  rfile = open(file,"r")
  rdscpt =""
  texsrc = ""
  $texfile = ""
  count = 0

  rfile.each{ |i|
    if count == 1
      if  i =~ /^=end tex/
	count = 0
	tex2png($texfile,texsrc)
#	rdscpt << %|((:<img src="tex/#{$texfile}.png">:)) |
	texsrc = ""
      else
	texsrc << i 
      end
    else 
      if  i =~ /^=begin tex/
	$texfile = i.split(" ")[2]
	count = 1 
      else 
	rdscpt << i 
      end
    end
  }

  rfile.close
  File.delete(outfile) if File.exist?(outfile)
  wfile = open(outfile,"w") 
  wfile.print rdscpt
  wfile.close
  #  File.rename("tmp.rd",file)
end


# rd から抽出した tex 部を latex2png で png に変換
def tex2png(texfile,texsrc)

  unless File.exist?(Dir.pwd + "/../tex/") 
    Dir.mkdir(Dir.pwd + "/../tex/",0775) 
  end
  cdir = Dir.pwd
  Dir.chdir(Dir.pwd + "/../tex")

#  File.delete(texfile + ".tex") if File.exist?(texfile + ".tex")

  if File.exist?(texfile + ".png")
    print "#{texfile}.png already exist\n" 
  else
    print "#{texfile}.png not found. now creating...\n" 
    tex = "\\documentclass[a4j,12pt]{article}\n"
    tex << "\\pagestyle{empty}\n"
    tex << "\\begin{document}\n"
    tex << texsrc
    tex << "\\end{document}\n" 
    wfile = open(texfile  + ".tex","w") 
    wfile.print tex
    wfile.close

#  `latex2png #{texfile}.tex > /dev/null 2> /dev/null`
    `/home/yukiko/bin/latex2png #{texfile}.tex > /dev/null 2> /dev/null`
#    File.delete(texfile + ".tex") if File.exist?(texfile + ".tex")  
  end

  Dir.chdir(cdir)

end



######################################################
if $0 == __FILE__
  file = Dir.pwd
  outfile = Dir.pwd
  opt = ARGV
  file = Dir.pwd + "/" + ARGV[0]
  if ARGV[1] == nil
    outfile = Dir.pwd + "/" + "tmp.rd" 
  else
    outfile = Dir.pwd + "/" + ARGV[1] 
  end
  print "filter_rd-y start\n"
  ruby_to_rd(file, outfile)
  tex_to_rd(outfile, outfile)
  print "filter_rd-y end\n"
end

