Rewritten the script to be more flexible and using less variables