Finally made the script work as required