Adapted OpenBSD's extract and insert methods.