Added error messages and tidied up code