Refactor Discovery.cpp.
Fix some edge case bugs with discovery on Windows.