added error handling and cleaned code up