Added more error handling and comments