Merge suggested fix from bug 7511 and enhance it