Reorganized some code to prevent a nullpointerexception.