Import and upgrade patch from pull request #603

See #603 for more details