Fix issue #365.
Tests for issue #365 and better fix for the issue.
Merge pull request #366 from danbruce/master

Fix issue #365.