Maybe it's just me, but figuring out this function and checking that it's correct took forever. Maybe a few more comments?