Improve patching mechanism and add more error checks.