Refactoring to use fewer variables and branches. Adding some error
checking, but does not alert user.