refactored with @jugglinmike's suggestions