tidied error handling significantly