Improve error handling and memory usage