Remake of PR 1317

This is a remake of PR #1317. The commit messages were fixed and the patches verified.