fix NPE; refactor