This is a cleaned up version of JoelKatz’ work, originally found in pull request #568.
A few minor didnt-check-error-return bugs were fixed. All other changes were comment- or coding style-related changes unrelated to behavior.
Should be upstream-ready at this point. Is in use at a few pools and other places.