refining code and error handling