Fix possible NPE and crashes
Merge pull request #1822 from Prototik/npe

Fix possible NPE