Bug fix the clean up code and improve error messages