added some null checking and error handling