Added safety checks on array access