Patch fixes from private fork.
6bfb68d0c6a69b408316581480cdb45dfd81a45b
b934b9261a0e9a962169f751db16e98c1ca14c65
c6f1ca58285b9c763a9710b1c9db8430cdfbe210