added error handling, cleaned code