Fixes cleanup issues and improves cleanup logic.

Caught some big cleanup bugs -- this fixes them.