Added extensive error handling and logging