making the script more robust and adding some comments