Fixed NullReferenceExceptions and infinite loops