better error handling, cleanup