revised code from commit a8f38ef as skinner recommended