Cherry picked better NBT handling from aadnk.