added better stopping conditions