Some cleanup and slightly better error handling