Added some additional error checking and changed some logic flow.