Fixed NPE; minor refactoring