Some smarter logic as suggested by Howard Miller. (cherry picked from commit b63fa387fffe61b546842dc2fab4380510216dcb)