Fix before/after code logic for KEEP behavior