added error handling and some testing code