#!/usr/bin/ruby
require "getopts.rb"
Code = "sjis"
Form = "【%s=>%s】"
Log = "gsub.log"

getopts("", "f:gsub.tbl")
Tbl = $OPT_f

Trans, TransOrder = {}, []
def Trans.[]=(x, y)
  TransOrder << x; super
end

def Trans.each # ハッシュ順序付きeach
  TransOrder.each do |x| yield(x, Trans[x]) end
end

def backupfile(file)
  bak = file + ".000"
  bak.succ! while File.exist?(bak)
  bak
end

def substitute(ifile, ofile)
  contents = open(ifile) do |f| f.readlines end
  logs = []
  count = 0
  open(ofile, "w") do |t|
    contents.each_with_index do |line, ln|
      c = 0
      line0, line1 = line.dup, line.dup
      Trans.each do |reg, str|
	if line0.gsub!(reg){|s|
	    c += 1
	    count += 1
	    Trans[reg]
	  }
	  line1.gsub!(reg) do |s|
	    Form % [s, Trans[reg]]
	  end
	end
      end
      t.print line0
      logs << "%s:%d:%s" % [ofile, ln+1, line1] if c > 0
    end
  end
  open(Log, "a") do |log| log << logs; end if count > 0
  count
end

# 変換表をハッシュで記録
File.foreach(Tbl) do |line|
  line.chop!
  next if /^#/ =~ line
  break if line == ""
  str0, str1 = line.split(/\t+/)
  raise "Illegal line: #{line}" unless str1
  Trans[Regexp.new(str0, false, Code)] = str1
end

$stdout.sync = true
ARGV.each do |fname|
  bak = backupfile(fname)           # バックアップファイル名
  File.rename(fname, bak)           # バックアップ
  print "processing #{fname} ... "
  count = substitute(bak, fname)    # 置換
  if count > 0
    puts "done. (change: #{count})\n"
  else
    File.unlink(bak)
    puts "no change."
  end
end
