Implementation of issue #1582

I think it is ready for tests and review.