Fixed a bug and enhanced the script.