What that's doing is actually quite complicated, so I added some comments.