Generalize patching funciton