Fixed a number of bugs to avoid NPE in various cases