issue #540: merged patch by @guidoreina, added test
merged patches by @guidoreina