Ported a few useful things from NightLabs' codebase.