cleaned code, improved error handling