Is this guaranteed to work?  Perhaps the `if`s that follow should be wrapped in a check to prevent dereferencing undefined?