Fixing NPEs and ClassCastExceptions