Mostly fix #340

You might be able to come up with something better, but this is at least an improvement and simplification.