Fix and tests for http://stackoverflow.com/q/23696254/23354