rewrote changes for PR #1303 and added a test