Changed error handling to be cleaner

This uses gotos to centralise the cleanup. I quite like gotos...