Modified criteria handling and explained the optimization in comments