Test and fix for issue #1568. Wasn't testing for end element in the right place.