Encapsulated code & added general error handling