Carsten's algorithm from origin/algorithm