Doesn't this algorithm already exist somewhere?