Merge from unholyhen

This merge was difficult to do and was instead done manually.
From commit 69fe2ba1eb9ce896859d96f7eafaf27f4fb38f67 of unholyhen's
master branch.