Added additional sanity checks to avoid undefined errors