Applied fixes from the 1.5.2 branch:

e6f93c81a27c39090d53511f3e3579bfd6b00fe3
8c23bf64f6d57681eee3d73b85c6b95a94f1048b
5fa5bf6f90fd6c6e9dbdba4f63e78b8cc5c1326e