Adapted wil1471's pull request #385 to master