Added more defensive code to deal with certain situations.