This needs some comments to explain what this code is doing, as it's really not obvious without all the context.