Smarter, more comprehensive, cleanup algorithm