Fixed problems covered by current tests.
Partial revert of c4add9ccd5775c9d6d04ff20febf4f1b0852e550.