def usage
  puts "Usage: ruby " + $0 + " targetdir *.rb"
  exit
end

if targetdir = ARGV.shift
  targetdir.sub!(/\/$/, '') #/
  unless File.directory?(targetdir)
    usage
  end
else
  usage
end

def detub(line, tabwidth = 4)
  line = line.dup
  while line.sub!(/\t/) { " " * (tabwidth - $~.begin(0) % tabwidth) }
  end
  line
end

def mktitle(head)
  title = "#  #{head}  #"
  f = ""
  f << "#" * title.size << "\n"
  f << "#" <<  " " * (title.size-2) << "#\n"
  f << title << "\n"
  f << "#" <<  " " * (title.size-2) << "#\n"
  f << "#" * title.size << "\n"
  f
end

ARGV.each do |filename|
  sw = false
  testexist = false
  testbuff = ""
  File.foreach(filename) do |line|
    if line =~ /^if\s+\$0\s*==\s*__FILE__\b/ or
	line =~ /^if\s+__FILE__\s*==\s*\$0\b/
      sw = true
    elsif line =~ /^end\s*/
      sw = false
      testexist = true if testbuff.size > 0
    else
      if sw
	testbuff << detub(line, 4).sub(/^  /, '')
      end
    end
  end
  if testexist
    script = File.basename(filename)
    newname = targetdir + "/" + "test-" + script
    if File.exist?(newname)
      puts "warning: " + newname + " exist."
      exit
    end
    open(newname, "w") do |f|
      f << mktitle("This is test script for '#{script}'")
      f << "require \"#{script}\"\n"
      f << testbuff
    end
    puts "extract: " + newname + " exist."
  end
end
