revised code from Ned's comments