This algorithm is adapted from Raymond Chen's code: https://blogs.msdn.microsoft.com/oldnewthing/20170109-00/?p=95145