added the possibility to end the loop when fo the first time M reaches M_max