fix indexing bug in Image::replace
organize code for splitting up patching