Added safety logic to prevent undefined access.