added error handling and document validation