modified based on input from @jrrideout