Code simplified; extended to NxM clusters.