Refactored this script. More readable now