Add several NULL checks and handling for edge cases.