Add null checks to fix #521.