copied NPE fixes from master