added error handling, simplified functions