Fix a nasty memory/proc leak pointed out by @Xanders. Fixes #1020.