slightly more robust primitive cell algorithm