Fixed several bugs in the script