Recommit of 0d2860b7 with extra test cases fixed.
mentioned in commit b433076f
mentioned in commit 98a15dd2