Generalized the algorithm a bit.