#/usr/bin/ruby

require 'erb'
erb = ERB.new(open('php2ruby.erb') {|f| f.read})
code = data = file = ''

Dir['/home/rubys/cvs/pecl/ibm_db2/tests/test_*.phpt'].each do |file|
  code = open(file) {|f| f.read}.scan(/<\?php(.*?)\?>/m)[-1][0].strip
  data = open(file) {|f| f.read}.scan(/\n--EXPECTF?--\n(.*)/m)[-1][0].chomp

  # db2
  code.gsub! /db2_/i, 'DB2::'

  # administrivia
  code.gsub! /require_once\('.*?'\);\s*/, ''

  # data structures
  code.gsub! /array\((.*?)\)/m, '{\1}'

  # control structures
  code.gsub! /if \((.*?)\) \{/, 'if \1'
  code.gsub! /\s*\{\s*$/, ''
  code.gsub! /\}\s*else/, 'else'
  code.gsub! /^(\s*)\}/, '\1end'

  # printing
  code.gsub! /^(\s*)echo /, '\1puts'
  code.gsub! 'printf (', 'printf('
  code.gsub! /^(\s*)print (.*);/ do
    pre,chunks = $1, $2.split(' . ')
    chunks = chunks.map do |chunk|
       if chunk[0] == ?" and chunk[-1] == ?"
        chunk[1..-2]
      else
        '#{' + chunk.gsub('$','') + '}'
      end
    end
    pre + 'puts "' + chunks.join('') + '"'
  end

  # string interpolation
  chunks = code.split('"')
  (1..(chunks.length-1)/2).each {|i| chunks[i*2-1].gsub!(/\$(\w+)/,'#{\1}')}
  code = chunks.join('"')
  
  # php => ruby
  code.gsub! /;$/, ''
  code.gsub! '$', ''

  # indentation
  code.gsub!(/^( *)/) {' ' * (6 + $1.length/2)}

  # output code
  if file.gsub! /.*?(\w+)\.\w+$/, '\1.rb'
    open("tests/#{file}",'w') {|$stdout| erb.run} 
  end
end
