Termination by count and optimization