Refine code
Improve error handling