Added some guards against pathological cases in the generic algorithm.