Added checks to prevent crashes