nice algorithm.