Added safeguards to prevent crashes.