Fixing several bugs in the script