#!/usr/bin/env ruby
$myDir = File.expand_path(Dir.pwd)
require 'fileutils'
puts $myDir

def updateFile(name)
  inhalt = IO.readlines(name)
  found = false
  ausgabe = []
  inhalt.each{ |x|
# tried converting but still had problems
#    x.gsub!('\inputencoding utf8','\inputencoding utf8-plain')

    if /begin_inset/.match(x) and /Include/.match(x)
      x.gsub!('.tex', '.lyx')
    end
    if /images\//.match(x)
      wo = File.dirname(File.expand_path(name))
      relatif = ""
      while wo.length>1 and wo != $myDir
             relatif += "../"
             wo = File.dirname(wo)
      end
      x.sub!('images/', relatif+'images/')
    end

    if !/images\//.match(x) or /png/.match(x)
    then
      ausgabe << x
    else
      changed = x.chomp! + ".png\n"
      puts changed
      ausgabe << changed
    end
  }
  datei=File.open(name, "w+")
  datei.puts ausgabe
  datei.close
end


#Dir.glob("elexis.tex").each { |x|
Dir.glob("**/*.tex").each { |x|
#Dir.glob("views/stammdaten.tex").each { |x|
	cmd = "/usr/bin/tex2lyx #{x}"
        lyxName = x.sub('.tex','.lyx')
        File.delete(lyxName) if File.exists?(lyxName)
	puts cmd
	exit if !system(cmd)
        updateFile(lyxName)
}
