incorporate code improvements from @ali-graham - https://gist.github.com/ali-graham/7da00d9719addef19eb4