Added error handling and cleaned code