some improvements suggested by @aelgru