Got the code working and added some slightly better error handling