Please add comments to this function it's really hard to follow the logic.