Fixed a bunch of NPEs and bug #2271 and bug #2272