Re-land patches from bug 566746 and bug 697377 now that bug 851641 is addressed
Bug 566746 - various fixes to sanitize().  r=mak