Cleaned up some code with try statments and improved error handling