Cleaned up code some, added more error handling where applicable