incorporating Alex's improvements to my implementation