Add checks to prevent NullPointerExceptions in some cases.