Refactoring of patch from 7humblerocks and added test.