Improved logic; feedback from Greg Dehmlow.