NPE and memory bugfix