bug 33160, original patch and testcase supplied by Amol Deshmukh.. thanks. This version slightly more generic