Small improvement to avoid NPE, misc cleanups
Added type casting