Updated and tested script. Fixed a bug with an undefined variable.