# -*- ruby -*-

require 'mkmf'
require 'xtemplate'
begin
  require 'xtemplate/yaml'
rescue LoadError
end

RUBY = Config::CONFIG['RUBY_INSTALL_NAME']
PREFIX = Config::CONFIG['exec_prefix']

scripts = Dir.glob("samples/sample[0-9].rb").sort
scripts += Dir.glob("samples/sample[0-9][0-9].rb").sort
scripts += Dir.glob("samples/sampleX[0-9].rb").sort
scripts += Dir.glob("samples/sampleX[0-9][0-9].rb").sort
scripts += Dir.glob("samples/test[0-9].rb").sort
scripts += Dir.glob("samples/test[0-9][0-9].rb").sort
#scripts += Dir.glob("samples/sampleY[0-9].rb").sort
#scripts += Dir.glob("samples/sampleY[0-9][0-9].rb").sort

def print(*msg)
  $result << msg.join
end

def puts(*msg)
  $result << msg.join("\n") << "\n"
end

def p(val)
  $result << val.inspect << "\n"
end

$time = 0
def time()
  s_time = Time.now
  yield()
  e_time = Time.now
  d = e_time - s_time
  $time += d
  d
end

n_test = 0
n_fail = 0
scripts.each{|script|
  if( script =~ /sampleY/ && !defined?(YAML) )
    next
  end
  n_test += 1
  case n_test
  when 1,2,3,21
    XTemplate::use_default_xpath()
    XTemplate::use_simple_expand()
  when 4,5,22,23,24,27
    XTemplate::use_simple_xpath()
    XTemplate::use_default_expand()
  else
    XTemplate::use_default_xpath()
    XTemplate::use_default_expand()
  end
  result = File.open(script.gsub(/\.rb$/,".out")){|f| f.read}
  $result = ""
  t = time{ load script }
  if( File.exist?("tmp/samples") )
    File.open("tmp/#{script.gsub(/\.rb$/,'.out')}","w"){|f| f.write($result)}
  end
  if( result.strip == $result.strip )
    $stdout.print("#{script}: ok")
  else
    $stdout.print("#{script}: fail")
    n_fail += 1
  end
  $stdout.print(" #{t}(s) #{$time}(s)\n")
}

$result = ""
time{ load "samples/xpath.rb" }
$result.each_line{|line|
  $stdout.print(line)
  n_test += 1
  if( line =~ /fail(\s*)$/ )
    n_fail += 1
  end
}

$stdout.print("\n", "#{n_test} test(s), #{n_fail} fail(s), time #{$time}(s)\n")
if( defined?(REXML) )
  $stdout.print("(Failure in sample7.rb is expected.)\n")
end
