Converted the script to use functions, rather than just a linear mess, and also added very basic error handling