Added in David Crocker's improvements (many thanks to him).