Fixed error in script (and made it slightly more elegant).