Re-lands 04aa943b with modifications to fix tests. I originally reverted this because it caused a test to fail on Linux. The problem was that I inverted a condition on accident.