Fix code logic. Fixes #581. Fixes #574.