#! /usr/bin/ruby

require "rexml/document"

TARGET = String.new( ARGV[0] )
OUTPUT = String.new( ARGV[0] ) << ".patched"
XPATCH = ARGV[1]

def hex2binary( h ) return h.delete(' ').to_a.pack('H*').unpack('C*') end

def dump(p)

  i = 0 
  p.each {|e| 
    s = e.to_s.strip.split("\n")[0] 
    print "#{i}: #{s} #<#{e.class}>\n" 
    if e.is_a?(REXML::Element) then dump( e ) end
    i += 1 
  }

end

doc = nil 
File.open( XPATCH ) {|fp| 
  doc = REXML::Document.new fp 
} 

i = 0
PATCH = Array.new
doc.elements.each('/binchg/patch/') { |e|

	child = Hash[ *['name', e.elements['name'].get_text,
			  'org',  hex2binary( e.elements['org'].text ),
			  'mod',  hex2binary( e.elements['mod'].text ) ] ]
	PATCH.insert( i,  child )
	i += 1
}

size = File.size( TARGET )

infile = open( TARGET )
infile.binmode

tmp_buffer = infile.read( size )

buf = tmp_buffer.unpack("C*")

i = 0
while( i <  buf.length() )
	PATCH.each { |p|

		orglen = p["org"].length()

		if (buf.length() - i ) > orglen then
			if buf[ i, orglen ] == p['org'] then
				printf( "0x%08x hit-> %s\n", i, p['name'] )
				buf[ i, orglen ] = p['mod']
			end
		end
	}

	i += 1
end

#p buf

outfile = open( OUTPUT, "w" )
outfile.write( buf.pack( "C*" ) )


