Fixes for cast exception and checking for null.