added some error handling and debugging features