enhanced error handling and some cleanup