Added some error handling and modified logic