slowly trying to figure out this algorithm