JENKINS-13732

Implements suggestion from JENKINS-13732 as well as some additional code cleanups and error checking.