NPE bugfixes and code cleanup