patch from Brandon Uhlman (with slight alteration discussed and 1 added sanity check...