My attempt a fix for #644.

New test included. Seems to work. Please review.