implemented optimization suggested by Robert Fairlie-Cuninghame