Some improvements

I've made some cosmetic improvements to the script, fixed the logic a bit, and made some suggestions for additional improvements.