Refactor code, add some basic error handling