Tidied up error handling. Also, const const const const const const const const const const const const const const const const const const const const const const const const const const const const to stop myself doing silly things in future, and avoid some compiler warnings.