Land the majority of pull request #608.

I reorganized the commits a bit and squashed a few of them. This does not include https://github.com/maximuska/ninja/commit/123d3773cb23a9fa51573aa5eb74a00735e0203e since that seems unrelated to #603. I'll land that in a separate pull request.