Back-port miscellaneous fixes from internal branch (mostly portability fixes).

These are changes that are in our internal branch, but somehow were skipped
so far. It was done using visual comparison of the branches --
it is likely that changes are being carried on the wrong way
18 files changed