Added some additional safety checks and handling to prevent failure for some problems.