Added some basic error handling. Refactor to coding standards