Attaching a revised version of the 2nd patch, with the tweaks, a couple more tests, and no longer leaking.