Fixed and cleaned up the script code