Some cleanup and error handling