def print_function_event_handle(cname, handles)
  print <<EOT

function #{cname}_event_handle(This, name: Tvalue): Tvalue; cdecl;
begin
  EventHandle(This, name, [#{handles}]);
  result := Qnil;
end;
EOT
end

def print_define_event_handle(cname)
  print <<EOT
  rb_define_method(c#{cname}, 'event_handle', @#{cname}_event_handle, 1);
EOT
end

def trans(i, o)
$defout = o
cname = nil
handles = nil
handled = nil
while line = i.gets
  case line
  when /^\s*procedure\s+(\w+)_setup\b/
    cname = $1
  when /^\s*AssignPropMethod\(\w+,\s*\[(.+)\]\);/
    handles = $1
    print '//  ', line
    next
  when /^end;$/
    print line
    if cname and handles
      print_function_event_handle(cname, handles)
      handles = nil
      STDOUT.print ": #{cname} implemented event_handle\n"
      handled = true
    end
    next
  when /^\s*(rb_define_singleton_method|DefineSingletonMethod)\(.+'new'.+\);/
    # 複数回 Define している .pas ではうまくいかない
    # cname をこの行から得る必要がある
    if cname and handled
      print_define_event_handle(cname)
      handled = nil
      STDOUT.print ": #{cname} defined event_handle\n"
    end
    print line
    next
  end
  print line
end
if handled
  STDOUT.print "#{i.path}(#{i.lineno}): ! #{cname} not defined event_handle\n"
end
end

text_exts = %w[
  pas
  dpr
]

def run(src)
  tmp = src + '~'
  File.rename src, tmp
  open(tmp, 'r'){|i|
  open(src, 'w'){|o|
    trans i, o
  }}
end

Dir.glob('**/*'){|entry|
  pos = entry.rindex('.')
  next if pos.nil?
  ext = entry[pos+1..-1]
  if text_exts.include? ext
    $stderr.print "run #{entry}\n"
    run entry
  end
}
